python - 在 python 中的列表中定位列表元素的最快方法是什么?

标签 python list python-2.7

列表类似这样:

[["12", "stuA", "stuB"], ["51", "stuC", "stuD"], ..., ["3234", "moreStuff", "andMore"]]

现在我只需要通过它的第一个值(例如 "332")来定位一个项目(获取索引)。除了从第一个开始迭代以与每个值进行比较之外,还有什么更好的方法可以做到这一点吗?

代码:

index = 0
for item in thelist:
    if item[0] == "332":
         print index

    index = index + 1

最佳答案

否。如果不迭代,您将无法找到它,除非列表已经排序。您可以像这样改进您的代码,使用 enumerate和列表理解。

[index for index, item in enumerate(thelist) if item[0] == "332"]

这将给出第一个元素为 332 的所有元素的索引。

如果您知道 332 只出现一次,您可以这样做

def getIndex():
    for index, item in enumerate(thelist):
       if item[0] == "332":
          return index

关于python - 在 python 中的列表中定位列表元素的最快方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20683167/

相关文章:

python - 在 cryptography-0.8.2 python 安装中出现 "weak reference"错误

python - 如何获取异常字典信息?

python - 如何将 int 转换为 4 字节十六进制

python - 我有一长串需要排序的元组,例如。 [ ('12/2010' , 196.9876), ('12/2010' , 654.9876), ('11/2010' , 234.9876)…………]

python - Kivy花园安装

python - 如何在Intel & python2.7上安装pytorch?

python - 如何使用 OpenCV 生成类似纸张的背景

python - sklearn : Naive Bayes classifier gives low accuracy

python - 合并两个列表中的元素

python - 在遍历列表时在数据框的一行中添加多个值