繁体   English   中英

给定一个包含它的列表在 Python 中找到一个项目的索引的最快方法是什么?

[英]Whats the fastest way of finding the indexes of an item given a list containing it in Python?

我有一个这样的列表,但有数千甚至数百万个元素:

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]

您可以使用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]

我相信这是最优化的;

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

暂无
暂无

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

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