根据位置将嵌套列表中的元素提取到单独的列表中 [英] Extract elements in a nested list into separate lists according to the positions

查看:48
本文介绍了根据位置将嵌套列表中的元素提取到单独的列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个嵌套列表说:

[[1,2],
 [3,4],
 [5,6]]

如何从此列表中提取列([1,3,5][2,4,6])pandas DataFramenp 数组 像:

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 返回一个元组迭代器,然后将其解包为 list1list2,如果需要列表,maplist 然后解压:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆