user12341266
user12341266

Reputation:

Get index value from a list

I have two lists list1 is a multidimensional list and list is a single dimensional list. I am writing a code such that if list1 has element which is in list2 then I wanted to know at what index value of list2 is been selected My code is:

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])

my list is of length 6 million which is a multidimensional for eg:

[['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']]

How can I find the index of list2 in code specified. Thanking you in advance

Upvotes: 0

Views: 88

Answers (2)

MisterMiyagi
MisterMiyagi

Reputation: 50076

You can directly search for the index of each list1 element in list2:

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

Note that this is very slow if list1 and list2 are not small -- list2 is scanned from the beginning for each element in list1. To look up multiple elements, build a lookup structure first:

# map from element to index
lookup2 = {element: idx for idx, element in enumerate(list2)}
for element in list1:
    try:
        print(element, '@', lookup2[element[0]]):
    except ValueError:
        pass

This scans each list only once.

Upvotes: 1

Gautham Pughazhendhi
Gautham Pughazhendhi

Reputation: 342

You could do something like this,

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

Upvotes: 1

Related Questions