Python 列表和列表项匹配 - 我的代码/推理可以改进吗?

标签 python list while-loop

查询级别:初级

作为学习练习的一部分,我编写了代码,该代码必须检查字符串(因为它是通过 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' 

此代码有效,但如何改进我的代码(以及我的推理/方法)? 我觉得我的 IFWHILEFOR 语句的嵌套有点矫枉过正。

编辑 感谢 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/

相关文章:

java - 从列表中添加和检索对象

python-3.x - 如何获得两个列表之间的对称差异?

python - while 循环的时间复杂度

while-loop - while (true) 与break 是不好的编程习惯吗?

python - 根据构造函数签名使用不同的类定义

python - 如何在一个脚本中从两个网站进行网络抓取?

python - 导入错误 : DLL load failed: The operating system cannot run %1. Python 2.7.12 |Anaconda 4.2.0(64 位)

python - 获取购买次数最多的前 10 件商品作为列表

list - Zenity - 不同的返回值

java - 为什么java中的while循环会运行?