python检查单词是否在列表的某些元素中

Sam*_*Sam 4 python list cpu-word

我想知道是否有更好的方法:

if word==wordList[0] or word==wordList[2] or word==wordList[3] or word==worldList[4]
Run Code Online (Sandbox Code Playgroud)

Vin*_*ard 7

word in wordList
Run Code Online (Sandbox Code Playgroud)

或者,如果你想先检查4,

word in wordList[:4]
Run Code Online (Sandbox Code Playgroud)


rob*_*ert 6

非常简单的任务,以及很多方法来处理它.精彩!这是我的想法:

如果您确定wordList很小(否则它可能效率太低),那么我建议使用这个:

b = word in (wordList[:1] + wordList[2:])
Run Code Online (Sandbox Code Playgroud)

否则我可能会这样做(仍然,这取决于!):

b = word in (w for i, w in enumerate(wordList) if i != 1)
Run Code Online (Sandbox Code Playgroud)

例如,如果要忽略多个索引:

ignore = frozenset([5, 17])
b = word in (w for i, w in enumerate(wordList) if i not in ignore)
Run Code Online (Sandbox Code Playgroud)

这是pythonic,它可以扩展.


但是,有一些值得注意的替代方案:

### Constructing a tuple ad-hoc. Easy to read/understand, but doesn't scale.
# Note lack of index 1.
b = word in (wordList[0], wordList[2], wordList[3], wordList[4])

### Playing around with iterators. Scales, but rather hard to understand.
from itertools import chain, islice
b = word in chain(islice(wordList, None, 1), islice(wordList, 2, None))

### More efficient, if condition is to be evaluated many times in a loop.
from itertools import chain
words = frozenset(chain(wordList[:1], wordList[2:]))
b = word in words
Run Code Online (Sandbox Code Playgroud)