How to reach a specific inner list in a nested list

Viewed 116

I have a nested list which doesn't split. Like:

list1 = [['New York; 4545; 45; 545; 545'],
         ['Berlin; 545; 454; 5645'],
         ['Paris; 5;;; 112']]

My list contains thousands of element like above. I want to reach a specific list. for example the list which contains 'Paris' and create another list from it.

BTW to clarify the problem; there are thousands of entries in the list and I don't know the index of the list which contains paris.

output may like:

list2 = ['Paris', 5, 112]

anyone has a idea?

4 Answers

To find a sublist containing a specific value, you can do this.

list1 = [['New York; 4545; 45; 545; 545'],
         ['Berlin; 545; 454; 5645'],
         ['Paris; 5;;; 112']]


list2 = [i for i in list1 if i[0].split(';')[0] == 'Paris']

Try This.

[element for element in list1 if 'Paris' in element[0]]

Not sure why each element in the list is a list with one string.

A pretty simple way to do this would be using pandas if you are fine with using external libraries.

This would give you all indices where 'Paris' is present irrespective of the position.

Given that the size of lists is huge, searching would be faster when using pandas.

import pandas as pd
temp_df=pd.DataFrame(list1)
indices_with_paris=list(temp_df[temp_df.loc[:,0].astype(str).str.contains('Paris')==True].index)

To get the values where 'Paris' is present

for indices in indices_with_paris:
   print(list1[indices][0].split(';'))

Output

['Paris', ' 5', '', '', ' 112']

This depends on a few things. To reach an entry in a list you want to use the index of this entry

So if you have your list1 you access "Paris" by calling list1[2]

(indexes start at 0)

If you want to access it not with the index but by "name" you should either change the datatype to a dictionary and use "paris" as a key, or you have to write a "search" function that loops over your list

A search function could look like this:

def search(cityname,listvar):
    for entry in listvar:
        if entry[0][:len(cityname)]==cityname:
            return entry[0].split(";")
Related