简体   繁体   English

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

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

I have a list like this but with thousands or maybe millions of elements:我有一个这样的列表,但有数千甚至数百万个元素:

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

What would be the most optimized code for finding all the elements indexes that contain the word "hi"?查找包含单词“hi”的所有元素索引的最优化代码是什么? In the given example above, it should return test[1] and test[2] .在上面给出的示例中,它应该返回test[1]test[2]

You can use enumerate and any to get the index of all elements that contains the word 'hi'您可以使用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]

I believe this is the most optimal;我相信这是最优化的;

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.

相关问题 在给定索引列表的情况下将多行插入数据帧的最快方法(python) - fastest way to insert multiple rows into a dataframe given a list of indexes (python) 在列表中查找项目索引的最快方法? - Fastest way to find Indexes of item in list? 在python中创建包含整数的类似列表的对象的最快方法 - Fastest way to make a list-like object containing integers in python 迭代包含 Python 中字符串的大型列表的最快方法? - Fastest way to iterate over a large list containing strings in Python? 从给定索引数组的 Python 列表中提取子列表的最快方法 - Fastest method for extracting sub-list from Python list given array of indexes 在 python 中找到特征值/向量的最快方法是什么? - whats the fastest way to find eigenvalues/vectors in python? 在python中找到两个列表列表之间的最常用元素的最快方法 - Fastest way of finding common elements between two list of lists in python Python, NLP - 查找包含给定单词列表的顶部文档 - Python, NLP - finding the top document containing given list of words Python:从给定属性的对象列表中提取子列表的最快方法 - Python: fastest way to extract sublist from a list of objects given an attribute 将列表项与python中的文本或字符串比较的最快方法 - Fastest way to compare list item against a junk of text or string in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM