在 if 语句中通过 list/string 进行同行迭代

same-line iteration through list/string in if statement

在python3.

a = True
b = 'ab'
letters = 'abcd'
if a and (b[0] in letters or b[1] in letters):
     do sth

如果 b 中的元素超过 2 个(例如 b = '5b$"£$$-'),是否有更有效的方法来遍历字符串?

谢谢

这个怎么样?

a = True
b = "..."
letters = "..."

if a and 1 in [1 for i in b if i in letters]:
    do ...

有一种可能:

if any(x in letters for x in b):
   do whatever

我能想到的可能的简单方法是:

1 - 使用 sets:

>>> a = True
>>> b = 'ab'
>>> letters = 'abcd'
>>> common = set(b).intersection(set(letters))
>>> if a and common:
    print 'There are letters common letters between b and letters'

2 - 使用内置方法 any :

>>> if a and any(i in letters for i in b):
    print 'There are letters common letters between b and letters'