我想知道这里是否有人在仍然使用基本字符串方法的同时,有一些浓缩此代码的技巧。该代码要求用户输入其名字,并使用函数和简单的字符串方法显示每个元音首次出现的索引。 这是我的代码:
def find_vowel():
name = input("What is your first name?: ")
name = name.lower()
if name.find('a') > 0:
print "There is an a in your name, first found at index",name.find('a')
if name.find('e') > 0:
print "There is an e in your name, first found at index",name.find('e')
if name.find('i') > 0:
print "There is an i in your name, first found at index",name.find('i')
if name.find('o') > 0:
print "There is an o in your name, first found at index",name.find('o')
if name.find('u') > 0:
print "There is an u in your name, first found at index",name.find('u')
find_vowel()
是否有任何关于压缩代码的反馈?预先感谢。
答案 0 :(得分:2)
而不是为每个元音重复所有这些代码,而是制作一个将其带入变量的循环,如下所示:
def find_vowel():
name = input("What is your first name?: ")
name = name.lower()
for vowel in ['a', 'e', 'i', 'o', 'u']:
if name.find(vowel) > 0:
print "There is an %c in your name, first found at index" % vowel,name.find(vowel)
find_vowel()
旁注:您可能不想使用input
,而是使用raw_input
,因为您仍在使用Python 2。
答案 1 :(得分:0)
如果切换到Python 3,其中void addEntry(PQ *pq, void *entry)
{
assert(pq != NULL);
int idx = pq->count;
if(pq->count == pq->length)
pq = realloc(pq, sizeof(PQ *) * (pq->length * 2));
pq->data[idx] = entry;
/* If the last element is greater than its parents, then swap them */
while(idx != 0 && pq->compare(pq->data[PARENT(idx)], pq->data[idx]) > 0)
{
swap(pq->data[PARENT(idx)], pq->data[idx]);
idx = PARENT(idx);
}
pq->count++;
return;
}
是函数而不是语句,则可以将其压缩为一行,作为列表理解。
print