Home > front end >  python | Get first elements of 2d list
python | Get first elements of 2d list

Time:10-29

i have following List:

j = [
    [(1, 100), (2, 80), (3, 40)],
    [(2, 80), (1, 30), (4, 50), (3, 60)],
    [(1, 40), (2, 70), (4, 30)]
]

How can i print every first element like this:

[1, 2 ,3]
[2, 1, 4, 3]
[1, 2, 4]

I tried with

for i in j:
print(i[0])

Thanks!

CodePudding user response:

Using zip and a list comprehension:

[next(zip(*i)) for i in j]

[(1, 2, 3), (2, 1, 4, 3), (1, 2, 4)]

Or using a nested loop:

[[v[0] for v in i] for i in j]

[[1, 2, 3], [2, 1, 4, 3], [1, 2, 4]]

CodePudding user response:

Try this:

for i in j:
    print([v[0] for v in i])

CodePudding user response:

You can use python's list comprehensions for each list i:

for i in j:
    print([x for x,y in i])

If you haven't used list comprehensions before, this means for each item in the list i (in this case a tuple (x,y)), use the value of x for this new list we are creating.

CodePudding user response:

The ugliest, least pythonic form, but easiest to understand:

for i in j:
   l=[]
   for m in i:
      l.append(m[0])
   print(l)
  • Related