我有一个这样的列表,但有数千甚至数百万个元素: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 回答
潇潇雨雨
TA贡献1833条经验 获得超4个赞
我相信这是最优化的;
word = "hi"
matches = []
for tupl in test:
for elem in tupl:
if word in elem:
matches.append(tupl)
break
慕侠2389804
TA贡献1719条经验 获得超6个赞
您可以使用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]
添加回答
举报
0/150
提交
取消