简体   繁体   English

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

[英]python check if word is in certain elements of a list

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

if word==wordList[0] or word==wordList[2] or word==wordList[3] or word==worldList[4]
word in wordList

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

word in wordList[:4]

Very simple task, and so many ways to deal with it. 非常简单的任务,以及很多方法来处理它。 Exciting! 精彩! Here is what I think: 这是我的想法:

If you know for sure that wordList is small (else it might be too inefficient), then I recommend using this one: 如果您确定wordList很小(否则它可能效率太低),那么我建议使用这个:

b = word in (wordList[:1] + wordList[2:])

Otherwise I would probably go for this (still, it depends!): 否则我可能会这样做(仍然,这取决于!):

b = word in (w for i, w in enumerate(wordList) if i != 1)

For example, if you want to ignore several indexes: 例如,如果要忽略多个索引:

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

This is pythonic and it scales. 这是pythonic,它可以扩展。


However, there are noteworthy alternatives: 但是,有一些值得注意的替代方案:

### 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

Have indexList be a list of the indicies you want to check (ie, [0,2,3] ) and have wordList be all the words you want to check. 让indexList成为您要检查的指标列表(即[0,2,3] ),并让wordList成为您要检查的所有单词。 Then, the following command will return the 0th, 2nd, and 3rd elements of wordList, as a list: 然后,以下命令将返回wordList的第0,第2和第3个元素,作为列表:

[wordList[i] for i in indexList]

This will return [wordList[0], wordList[2], wordList[3]] . 这将返回[wordList[0], wordList[2], wordList[3]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM