>>> l = ['S', 'R', 'D', 'W', 'V', 'Y', 'H', 'K', 'B', 'M']
>>> s = 'YTG'
>>> any(i in s for i in l)
True
>>> i
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'i' is not defined
使用列表理解列出所有匹配的字母:
^{pr2}$
这将保留l中的顺序;如果matching中的顺序无关紧要,则可以使用设置交集。我会在这里做一套:
l = set(['S', 'R', 'D', 'W', 'V', 'Y', 'H', 'K', 'B', 'M']) # Python 3 can use {...}
matching = l.intersection(s)
if matching:
print matching
any
将告诉您条件是True
还是{要计算实际的常用字母,只需创建一个
set
并执行交集:产生
{'Y'}
。在一个衬垫:
set(list(s)).intersection(set(l))
{'Y'}
根据@Martijn Pieters♦ 简单评论:
set(s).intersection(l)
会做到这一点,如@Jean fraçois Fabre的回答所示any()
产生True
或{使用列表理解列出所有匹配的字母:
^{pr2}$这将保留
l
中的顺序;如果matching
中的顺序无关紧要,则可以使用设置交集。我会在这里做一套:通过将
l
作为集合,Python可以迭代更短的s
字符串。在相关问题 更多 >
编程相关推荐