给定一个包含它的列表在 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]。


九州编程
浏览 120回答 2
2回答

潇潇雨雨

我相信这是最优化的;word = "hi"matches = []for tupl in test:    for elem in tupl:        if word in elem:            matches.append(tupl)            break

慕侠2389804

您可以使用enumerate和any获取包含单词“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]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python