加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 通过使用第一个数组项索引条目来合并两个数组?

发布时间:2020-12-20 11:27:15 所属栏目:Python 来源:网络整理
导读:假设我有 a = [1,2,1,3,2]b = [4,7,9,5,6,11] 我期待着 c = [[4,9],[7,11],[5]] 正如您可能看到生成的子列表位于列表a指向的索引处.我们如何在python中做? 解决方法 你可以使用defaultdict: from collections import defaultdict d = defaultdict(list) a
假设我有

a = [1,2,1,3,2]
b = [4,7,9,5,6,11]

我期待着

c = [[4,9],[7,11],[5]]

正如您可能看到生成的子列表位于列表a指向的索引处.我们如何在python中做?

解决方法

你可以使用defaultdict:

>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> a = [1,3]
>>> b = [4,11]
>>> for k,v in zip(a,b):
...     d[k].append(v)
... 
>>>[x[1] for x in sorted(d.items())]
[[4,[5,6],[11]]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读