Python 列表及列表项匹配 - 我可以改进我的代码/逻辑吗?
查询级别:初学者
作为一个学习练习,我写了一段代码,这段代码需要检查一个字符串(通过输入获取)是否与列表中的任何项的开头匹配,或者是否等于列表中的任何一项。
wordlist = ['hello', 'bye']
handlist = []
letter = raw_input('enter letter: ')
handlist.append(letter)
hand = "".join(handlist)
for item in wordlist:
if item.startswith(hand):
while item.startswith(hand):
if hand not in wordlist:
letter = raw_input('enter letter: ')
handlist.append(letter)
hand = "".join(handlist)
else: break
else: break
print 'you loose'
这段代码可以正常工作,但我想知道我的代码(以及我的思路/方法)如何能改进?我感觉我在使用IF
、WHILE
和FOR
语句时,可能有点过于复杂了。
编辑 感谢Dave的帮助,我能够大幅缩短和优化我的代码。
wordlist = ['hello','hamburger', 'bye', 'cello']
hand = ''
while any(item.startswith(hand) for item in wordlist):
if hand not in wordlist:
hand += raw_input('enter letter: ')
else: break
print 'you loose'
我很惊讶我最初的代码居然能工作……
1 个回答
7
首先,你不需要用到 handlist
这个变量;你可以直接把 raw_input
的值和 hand
连接起来。
你可以通过让 hand
从一开始就是一个空字符串来保存第一个 raw_input
,因为每个字符串都可以用 startswith("")
来判断为 True
。
最后,我们需要找出最好的方法来检查 wordlist
中的任何项是否以 hand
开头。我们可以用列表推导式来做到这一点:
[item for item in wordlist if item.startswith(hand)]
然后检查返回的列表长度是否大于零。
不过,更好的方法是,Python 有一个 any()
函数,它非常适合这个用途:如果可迭代对象中的任何元素为 True
,它就会返回 True
,所以我们只需要对 wordlist
中的每个成员使用 startswith()
来判断。
把这些都结合起来,我们可以得到:
wordlist = ['hello', 'bye']
hand = ""
while any(item.startswith(hand) for item in wordlist):
hand += raw_input('enter letter: ')
print 'you loose'