![](/img/trans.png)
[英]fastest way to insert multiple rows into a dataframe given a list of indexes (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]
。
您可以使用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]
我相信这是最优化的;
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.