根据位置将嵌套列表中的元素提取到单独的列表中 [英] Extract elements in a nested list into separate lists according to the positions
问题描述
我有一个嵌套列表说:
[[1,2],
[3,4],
[5,6]]
如何从此列表中提取列([1,3,5]
或 [2,4,6]
) 到 pandas DataFrame
或 np 数组
像:
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])
或
a = [[1,2],[3,4],[5,6]]
list(np.array(a)[:,0])
两者都产生 [1,3,5]
.
推荐答案
使用 zip
将您的列表解压为:
Use zip
to unpack you lists as:
a = [[1,2],[3,4],[5,6]]
list1, list2 = zip(*a)
zip
返回一个元组迭代器,然后将其解包为 list1
和 list2
,如果需要列表,map
到 list
然后解压:
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
聚合输入迭代中的元素.通过使用 zip(*a)
解包,我们使每个内部列表在 zip
中成为一个单独的可迭代对象,然后将组合"到 zip
中.每个元素中的元素根据它们的位置.
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.
这篇关于根据位置将嵌套列表中的元素提取到单独的列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!