gpt4 book ai didi

Python简洁性: Comparing string to multiple sets with return value

转载 作者:太空宇宙 更新时间:2023-11-03 14:40:11 24 4
gpt4 key购买 nike

我从未找到一种简洁的方法,就是将一个字符串与多个集合进行比较,或者可能是一个能够提供一些有意义的输出的长字符串。这是我当前的代码:

def input():  
text = input("Choose a number: ").lower()
if "1" in text or "one" in text: return 1
elif "2" in text or "two" in text: return 2
... and so on...
elif "9" in text or "nine" in text: return 9
else: return 0

考虑到它现在有多难看,我的目标是让它更加简洁。

另外,还有一点问题:这样做更快,还是:

    if any(x in text for x in (["1", "one"])): return 1  

哪一种被认为更主流?

抱歉;我的Python确实是入门级的。

--- 编辑 ---

对造成的困惑表示歉意;我实际上指的是更普遍的东西,例如:

def input():  
text = input("Give an input: ").lower()
if any(x in text for x in (["eggplant", "emoji", "purple"])): return 1
elif any(x in text for x in (["tomato", "red", "tomatina"])): return 2
... and so on...
elif any(x in text for x in (["lettuce", "green", "avatar"])): return 9
else: return 0

最佳答案

根据查询的规律性,您可以使用某种循环:

for i, s in enumerate('one two three four ... nine'.split(), 1):
if str(i) in text or s in text:
return i
return 0

关于Python简洁性: Comparing string to multiple sets with return value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46605717/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com