给定包含Python的列表的情况下,查找项目索引的最胖方法是什么

时间:2018-08-29 11:25:19

标签: python list find element

我有一个像这样的列表,但是有成千上万个元素:

test = [
  ("goodbye", "help", "buy","sell", "1.1.1.1", 25), 
  ("hi dude", "text", "friends","love", "blablabla", 14), 
  ("hi darling", "books", "letter","class", "club", 64)
]

查找包含单词“ hi”的所有元素索引的最优化代码是什么? 在上面给定的示例中,它应返回test[1]test[2]

2 个答案:

答案 0 :(得分:1)

您可以使用enumerateany来获取包含单词“ hi”的所有元素的索引。

>>> test = [("goodbye", "help", "buy","sell", "1.1.1.1", 25), ("hi dude", "text", "friends","love", "blablabla", 14), ("hi darling", "books", "letter","class", "club", 64)]
>>> [i for i,words in enumerate(test) if any('hi' in str(word) for word in words)]
[1, 2]

答案 1 :(得分:0)

我认为这是最佳选择;

word = "hi"
matches = []
for tupl in test:
    for elem in tupl:
        if word in elem:
            matches.append(tupl)
            break