在if语句中通过列表/字符串进行同一行迭代

时间:2015-12-04 03:05:39

标签: python loops if-statement iteration

在python 3中。

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

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

谢谢

3 个答案:

答案 0 :(得分:2)

这是一种可能性:

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

答案 1 :(得分:1)

这个怎么样?

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

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

答案 2 :(得分:1)

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

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'