从列表中获取索引值

时间:2019-11-08 04:21:15

标签: python python-3.x

我有两个清单 list1是多维列表,list是一维列表。我正在编写一个代码,如果list1具有位于list2中的元素,那么我想知道选择了list2的哪个索引值 我的代码是:

import tkinter as tk
from tkinter import filedialog
import numpy as np
import os
root= tk.Tk()
root.withdraw()
filepath =filedialog.askopenfilename(filetypes = (("trace files","*.trace"),("out files",".out")))
file=open(filepath)
file_path = file.name
ext= os.path.splitext(file_path)
readData=file.readlines()
list1=[]
list2=[]
pht=[[1,0]]
goodPred=0
badPred=0
count=0

for read in readData:
    split= read.split(' ')
    addr =split[0]
    action= split[1]
    list1.append([addr,action.strip()])

for i in range(len(list1)):
    if list1[i][0] in list2:
        # what to write here to get the index value of list2

    else:
        # print(list1[i][0])
        list2.append(list1[i])

我的列表的长度为600万,例如:

[['3086712356', 'T'], ['3086666061', 'T'], ['3086666125', 'T'], ['3086666139', 'N'], ['3086666210', 'N'], ['3086666562', 'T'], ['3086666511', 'N'], ['3086666521', 'T'], ['3086666298', 'T'], ['3086636165', 'N'], ['3086636212', 'N'], ['3086636284', 'T'], ['3086636227', 'T'], ['3086636317', 'N'], ['3086636348', 'N'], ['3086636360', 'N'], ['3086636380', 'N'], ['3086636256', 'N'], ['3086636284', 'N'], ['3086636256', 'N'], ['3086636284', 'T'], ['3086636227', 'N'], ['3086636232', 'N'], ['3086636256', 'N'], ['3086636284', 'T'], ['3086636227', 'N']]

如何在指定的代码中找到list2的索引。 预先谢谢你

2 个答案:

答案 0 :(得分:1)

您可以这样做,

for i in range(len(list1)):
    if list1[i][0] in list2:
        list2_index = list2.index(list1[i][0])

答案 1 :(得分:1)

您可以直接在list1中搜索每个list2元素的索引:

for element in list1:
    try:
        print(element, '@', list2.index(element[0]):
    except ValueError:
        pass

请注意,如果list1 list2不小,这会非常慢-从list2开始扫描{{1 }}。要查找多个元素,请首先构建查找结构:

list1

此选项仅扫描每个列表一次。