Python列表和列表项匹配-我的代码/推理可以改进吗?
查询级别:初学者 作为学习练习的一部分,我编写了一些代码,必须检查字符串(通过原始输入构建)是否匹配任何列表项的开头,以及是否等于任何列表项Python列表和列表项匹配-我的代码/推理可以改进吗?,python,list,while-loop,Python,List,While Loop,查询级别:初学者 作为学习练习的一部分,我编写了一些代码,必须检查字符串(通过原始输入构建)是否匹配任何列表项的开头,以及是否等于任何列表项 wordlist = ['hello', 'bye'] handlist = [] letter = raw_input('enter letter: ') handlist.append(letter) hand = "".join(handlist) for item in wordlist: if item.startswith(
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'
我很惊讶我的原始代码居然能工作…首先,您不需要
手册列表
变量;您只需将raw_input
的值与hand
连接即可
您可以将第一个原始输入
保存为空字符串,方法是使用hand
启动while
循环,因为每个字符串都有startswith(“”)
作为True
最后,我们需要找出最好的方法来查看wordlist
中的任何项目是否以hand
开头。对此,我们可以使用列表理解:
[item for item in wordlist if item.startswith(hand)]
如果大于零,则检查返回列表的长度
然而,更好的是,python有一个非常好的方法:如果iterable的任何元素是True
,它将返回True
,因此我们只需为单词列表的每个成员计算startswith()
综上所述,我们得到:
wordlist = ['hello', 'bye']
hand = ""
while any(item.startswith(hand) for item in wordlist):
hand += raw_input('enter letter: ')
print 'you loose'
+任何一个都是1。我不知道。(今天学习一些新东西-检查)@Space\u C0wb0y-还有all()
我会把它留到明天:)嗨,戴夫。太好了,谢谢!所以字符串,就像列表、字典和元组一样,也可以填充。它使“.join()部分变得多余。非常感谢。我将修改我的代码并发布它,看看它是否好。虽然你和我差不多。