Home > Mobile >  How to filter the elements from nested lists composed of strings
How to filter the elements from nested lists composed of strings

Time:04-29

I am trying to access elements from the nested lists. For example,

file = [["Name","Age","Medal","Location"],["Jack","31","Gold","China"],["Jim","29","Silver","US"]]

This data contains at least 3000 lists. I only want to put the data into a new list with the column Name and "Location"

Output should be: [["Name", "Location"], ["Jack", "China"], ["Jim", "US"]]

This looks like a data frame. But I cannot use any module to separate the columns. How can I code it using python built-in function and methods. I tried for loops but failed.

CodePudding user response:

[[item[0],item[-1]] for item in file]

CodePudding user response:

One easy way to do this is by using list comprehensions. Given that you want every first and fourth item in every one of your sublists, you can do something like

file = [
    ["Name", "Age", "Medal", "Location"],
    ["Jack", 31, "Gold", "China"],
    ["Jim", 29, "Silver", "US"]
]


new_list = [[sublist[0], sublist[3]] for sublist in file]

This list comprehension reads as: create a new list with its elements being lists populated by the first and the fourth element of every sublist in the file variable.

  • Related