简体   繁体   English

Python:从字典创建两个带有元组列表的列表

[英]Python: create two lists from dict with list of tuples

Given this dict: 鉴于此命令:

d={0: [(78.65, 89.86),
  (28.0, 23.0),
  (63.43, 9.29),
  (66.47, 55.47),
  (68.0, 4.5),
  (69.5, 59.0),
  (86.26, 1.65),
  (84.2, 56.2),
  (88.0, 18.53),
  (111.0, 40.0)], ...}

How do you create two lists, such that y takes the first element of each tuple and x takes the second, for each key in d ? 对于d中的每个键,如何创建两个列表,使得y占据每个元组的第一个元素, x占据第二个元组的第二个元素?

In the example above (only key=0 is shown) this would be: 在上面的示例中(仅显示key=0 ),它将是:

y=[78.65, 28.0, 63.43, 66.47, 68.0, 69.5, 86.26, 84.2, 88.0, 111.0]
x=[89.86, 23.0, 9.29, 55.47, 4.5, 59.0, 1.65, 56.2, 18.53, 40.0]

My attempt is wrong (I tried the x list only): 我的尝试是错误的(仅尝试了x列表):

for j,v in enumerate(d.values()):    
   x=[v[i[1]] for v in d.values() for i in v]

Because: 因为:

TypeError                                 Traceback (most recent call last)
<ipython-input-97-bdac6878fe6c> in <module>()
----> 1 x=[v[i[1]] for v in d.values() for i in v]

TypeError: list indices must be integers, not numpy.float64

What's wrong with this? 这怎么了

If I understood your comment correctly, you want to obtain the x and y coordinates of the tuple list that is associated with key 0 . 如果我正确理解了您的评论,则希望获取与键0关联的元组列表的xy坐标。 In that case you can simply use zip(..) and map(..) to list s: 在这种情况下,您可以简单地使用zip(..)map(..) list s:

y,x = map(list,zip(*d[0]))

If you do not want to change x and y later in your program - immutable lists are basically tuple s, you can omit the map(list,...) : 如果您不想稍后在程序中更改xy不可变列表基本上是tuple s,则可以省略map(list,...)

y,x = zip(*d[0]) # here x and y are tuples (and thus immutable)

Mind that if the dictionary contains two elements, like: 请注意,如果字典包含两个元素,例如:

{0:[(1,4),(2,5)],
 1:[(1,3),(0,2)]}

it will only process the data for the 0 key . 只会处理0键的数据 So y = [1,2] and x = [4,5] . 因此y = [1,2]x = [4,5]

Do you mean something like this? 你的意思是这样吗?

z = [i for v in d.values() for i in v]
x, y = zip(*z)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM