Home > Mobile >  How do you access specific elements from the nested lists
How do you access specific elements from the nested lists

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:

This is a list comprehension problem:

newfile = [row[0:2] for row in file]

CodePudding user response:

You can accomplish this by slicing your array. See below:

newArr = [r[0:2] for r in oldArr]

CodePudding user response:

If we have any sequential data type like lists, strings, tuples, bytes, bytearrays, and ranges, then Python supports slice notation and we can traverse every character in the given list using for loop.

if we have a 2-dimensional or nested list then

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


for r in file:
    print(r)

OUTPUT:-
    ['Name', 'Age', 'Medal', 'Location']
    ['Jack', '31', 'Gold', 'China']
    ['Jim', '29', 'Silver', 'US']

# ----------------------------------------------------------------
# if we want only specific elements 
# then we use the slicing method
# ----------------------------------------------------------------
for r in file:
    print(r[0:2])

OUTPUT:-
    ['Name', 'Age']
    ['Jack', '31']
    ['Jim', '29']

# ----------------------------------------------------------------
# if we want to output as a list
# then we can use single line for loop
# ----------------------------------------------------------------

newFile = [r for r in file]
print(newFile)

OUTPUT:
    [['Name', 'Age', 'Medal', 'Location'], ['Jack', '31', 'Gold', 'China'], ['Jim', '29', 'Silver', 'US']]







# ----------------------------------------------------------------
# Output should be: [[“Name”,”Age”],[“Jack”,”31”],[“Jim”,”29”]]
# ----------------------------------------------------------------
newFile = [r[0:2] for r in file]
print(newFile)

OUTPUT:
    [['Name', 'Age'], ['Jack', '31'], ['Jim', '29']]
  • Related