【问题标题】:python check if word is in certain elements of a listpython检查单词是否在列表的某些元素中
【发布时间】:2012-03-11 22:25:39
【问题描述】:

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

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

【问题讨论】:

  • 循环遍历列表并以这种方式检查它们。

标签: python list word


【解决方案1】:
word in wordList

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

word in wordList[:4]

【讨论】:

  • 我希望有类似“wordList 中的单词”之类的内容,但我想忽略第二个元素。
  • @Sam: word in wordList[0] + wordList[2:] 是最简洁的方式。请注意,它会创建一个新的列表对象,因此如果您的列表很昂贵,最好进行迭代。但是,您跳过一个元素的事实告诉我每个索引都有意义;为什么不使用其他集合类型? namedtuple?带有__contains__的自定义类?
  • 谢谢你,丹妮丝!我还是这门语言的新手,但我必须考虑创建一个结构。
【解决方案2】:

非常简单的任务,有很多方法可以处理它。令人兴奋!这是我的想法:

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

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

【讨论】:

  • 我最终使用了frozenset() 方法,谢谢!我原来的做法抛出了一个错误,因为它是一个列表列表,但这完美地工作!
【解决方案3】:

让 indexList 成为您要检查的索引列表(即[0,2,3]),让 wordList 成为您要检查的所有单词。然后,以下命令将返回 wordList 的第 0、第 2 和第 3 个元素,作为列表:

[wordList[i] for i in indexList]

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-24
    • 1970-01-01
    • 2020-07-06
    • 1970-01-01
    • 2012-04-03
    • 1970-01-01
    • 2012-05-11
    相关资源
    最近更新 更多