从Python中的字典中拉出两个值 [英] zip two values from the dictionary in Python

查看:186
本文介绍了从Python中的字典中拉出两个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Python numpy在字典中压缩两个值,但并不是很成功。我的意思是拉链是这样的:

I am trying to zip two values in a dictionary using Python numpy but it's not very successful. What I mean by zipping is something like this:


  1. 我有一个名为dict的字典,里面看起来像 { 'a0':[1,2,3],'a1':[4,5,6]}

  2. 然后我要压缩这个字典dict值为: [(1,4),(2,5),(3,6)] (每个键中的一个元素)

  1. I have a dictionary called dict, and inside looks like {'a0': [1, 2, 3], 'a1': [4, 5, 6]}.
  2. Then I want to zip this dictionary dict values to: [(1, 4), (2, 5), (3, 6)] (one element from each key)


推荐答案

您需要解压缩 dict.values() code>当传递到 zip()时。示例 -

You need to unpack dict.values() when passing onto zip() . Example -

>>> d = {'a0': [1, 2, 3], 'a1': [4, 5, 6]}
>>> zip(*d.values())
[(4, 1), (5, 2), (6, 3)]

请注意,使用这种方法,压缩的内部列表中的元素的顺序不能保证,因为字典本身没有任何秩序感。

Please note using this method, the order of elements in the zipped inner lists are not guaranteed, as dictionary itself does not have any sense of order.

如果您想要特定的订单,您需要在 zip()调用中显式。示例 -

If you want a specific order, you would need to be explicit in your zip() call. Example -

>>> zip(d['a0'], d['a1'])
[(1, 4), (2, 5), (3, 6)]

这篇关于从Python中的字典中拉出两个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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