python检查单词是否在列表的某些元素中 [英] python check if word is in certain elements of a list
本文介绍了python检查单词是否在列表的某些元素中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道是否有更好的放置方式:
I was wondering if there was a better way to put:
if word==wordList[0] or word==wordList[2] or word==wordList[3] or word==worldList[4]
推荐答案
非常简单的任务,以及多种处理方式.令人兴奋!这是我的想法:
Very simple task, and so many ways to deal with it. Exciting! Here is what I think:
如果您确定wordList很小(否则可能效率太低),那么我建议您使用此列表:
If you know for sure that wordList is small (else it might be too inefficient), then I recommend using this one:
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)
这是pythonic,并且可以缩放.
This is pythonic and it scales.
但是,还有一些值得注意的选择:
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
这篇关于python检查单词是否在列表的某些元素中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文