查询级别:初级
作为学习练习的一部分,我编写了代码,该代码必须检查字符串(因为它是通过 raw_input 构建的)是否匹配任何列表项的开头以及它是否等于任何列表项。
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'
我很惊讶我的原始代码完全有效...
最佳答案
首先,您不需要handlist
变量;您可以将 raw_input
的值与 hand
连接起来。
您可以通过将 hand
作为空字符串启动 while
循环来保存第一个 raw_input
,因为每个字符串都有 startswith( "")
为 True
。
最后,我们需要找出最佳方法来查看 wordlist
中是否有任何项目以 hand
开头。我们可以为此使用列表理解:
[item for item in wordlist if item.startswith(hand)]
然后检查返回列表的长度是否大于零。
然而,更好的是,python 有 the any()
function这是完美的:如果可迭代的任何元素为 True
,它返回 True
,因此我们只需为每个成员评估 startswith()
单词列表
。
将这些放在一起我们得到:
wordlist = ['hello', 'bye']
hand = ""
while any(item.startswith(hand) for item in wordlist):
hand += raw_input('enter letter: ')
print 'you loose'
关于Python 列表和列表项匹配 - 我的代码/推理可以改进吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3768702/