Reputation: 2699
I have a nested list say :
[[1,2],
[3,4],
[5,6]]
How can I extract a column from this list, (either [1,3,5]
or [2,4,6]
) without converting it into a pandas DataFrame
or an np array
like :
a = [[1,2],[3,4],[5,6]]
list(pd.DataFrame(a)[0])
or
a = [[1,2],[3,4],[5,6]]
list(np.array(a)[:,0])
which both yields [1,3,5]
.
Upvotes: 1
Views: 1373
Reputation: 11
I am a beginner in python, could you please try this.
a = [[1,2],[3,4],[5,6]]
for i in a:
print(i[0])
Upvotes: -1
Reputation: 88236
Use zip
to unpack you lists as:
a = [[1,2],[3,4],[5,6]]
list1, list2 = zip(*a)
zip
returns an iterator of tuples, which are then unpacked into list1
and list2
, if you want lists, map
to list
and then unpack:
list1, list2 = map(list,zip(*a))
print(list1)
[1, 3, 5]
print(list2)
[2, 4, 6]
zip
aggrates the elements from the input iterables. By unpacking with zip(*a)
, we're making each inner list a separate iterable in in zip
, which will then "combine" the elements in each of these according to their positions.
Upvotes: 2
Reputation: 1168
This might help if you want one-line list comprehension
:
a = [[1,2],[3,4],[5,6]]
print([[elem[i] for elem in a] for i in range(len(a[0]))])
NOTE: len(a[0])
is what I'm using , so this will work only for inner-lists of equal lengths
.
Upvotes: 0