2012-03-11 54 views
4

我想知道是否有把一个更好的方式列表中的某些元素:如果你想先检查4或蟒蛇检查,如果字是在

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

遍历目录,查看他们的方式。 – twain249 2012-03-11 22:27:45

+0

重要吗? – 2015-06-29 20:41:43

回答

6

非常简单的任务,以及处理它的方法很多。精彩!以下是我认为:

如果你肯定知道单词表很小(否则它可能是效率太低),那么我建议使用这一个:

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

否则我会可能去这个(当然,这取决于!):

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

例如,如果你想忽略的几个指标:

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

这是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 
+0

我结束了使用frozenset()方法,谢谢!我做的原始方式抛出一个错误,因为它是一个列表清单,但是这个工作完美! – Sam 2012-03-11 23:21:06

7
word in wordList 

word in wordList[:4] 
+0

我希望能够像“wordList中的词”这样的东西,但我想忽略第二个元素。 – Sam 2012-03-11 22:35:25

+0

@Sam:wordList [0] + wordList [2:]'是最简单的方法。请注意,它会创建一个新的列表对象,所以如果您的列表很昂贵,最好迭代。然而,你跳过一个元素的事实告诉我,每个索引都意味着什么;你为什么不使用另一种集合类型? 'namedtuple'?具有'__contains__'的自定义类? – Daenyth 2012-03-11 22:40:29

+0

谢谢Daenyth!我对这门语言还不熟悉,但我必须考虑创建一个结构。 – Sam 2012-03-11 22:42:46

1

有没有indexList是你想检查的指示名单(即,[0,2,3]),并有wordList是你想检查的所有单词。然后,下面的命令将返回0号,2号和单词表的第三个要素,作为一个列表:

[wordList[i] for i in indexList] 

这将返回[wordList[0], wordList[2], wordList[3]]