社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
私信  •  关注

Vishvajit Pathak hamid

Vishvajit Pathak hamid 最近创建的主题
Vishvajit Pathak hamid 最近回复了
8 年前
回复了 Vishvajit Pathak hamid 创建的主题 » 需要有关python 3.7的简单脚本的帮助[duplicate]

如果要使用If、else语句,则以下是另一种解决方案:

myList = []
aList = [0, 1, 3]

for l in aList:
    if l==0: myList.append('c')
    elif l==1: myList.append('d')
    elif l==2: myList.append('e')
    elif l==3: myList.append('f')

print(myList)
8 年前
回复了 Vishvajit Pathak hamid 创建的主题 » 需要有关python 3.7的简单脚本的帮助[duplicate]

这里提供的所有优秀答案都集中在原海报的具体要求上,并集中在 if 1 in {x,y,z} 由Martijn Pieters提出的解决方案。
他们忽略的是这个问题更广泛的含义:
如何针对多个值测试一个变量?
如果使用字符串,例如:
测试字符串“Wild”是否有多个值

>>> x = "Wild things"
>>> y = "throttle it back"
>>> z = "in the beginning"
>>> if "Wild" in {x, y, z}: print (True)
... 

或

>>> x = "Wild things"
>>> y = "throttle it back"
>>> z = "in the beginning"
>>> if "Wild" in [x, y, z]: print (True)
... 

在这种情况下,最容易转换为字符串

>>> [x, y, z]
['Wild things', 'throttle it back', 'in the beginning']
>>> {x, y, z}
{'in the beginning', 'throttle it back', 'Wild things'}
>>> 

>>> if "Wild" in str([x, y, z]): print (True)
... 
True
>>> if "Wild" in str({x, y, z}): print (True)
... 
True

但是,正如 @codeforester ,使用此方法将丢失单词边界,如:

>>> x=['Wild things', 'throttle it back', 'in the beginning']
>>> if "rot" in str(x): print(True)
... 
True

三个字母 rot 在列表中确实存在组合,但不作为单个单词存在。测试“rot”将失败,但如果其中一个列表项是“rot in hell”,那也将失败。
结果是,如果使用此方法,请小心搜索条件,并注意它确实有此限制。