简体   繁体   English

从列表中提取x和y值

[英]Extract x and y values from a list

I have list like this: 我有这样的列表:

pp=[[0,0] , [-1,5], [2,3], [1,5], [3,6], [4,5], [5,3], [8,-2], [4, -4], [2, -5]]

And I want to extract x and y values in separate lists like: 我想在单独的列表中提取x和y值,如:

ppx= [0, -1, 2, 1, 3, 4, 5, 8, 4, 2]

Use zip() to separate the coordinates: 使用zip()分隔坐标:

ppx, ppy = zip(*pp)

This produces tuples; 这会产生元组; these are easily enough mapped to list objects: 这些很容易映射到list对象:

ppx, ppy = map(list, zip(*pp))

This works in both Python 2 and 3 (where the map() iterator is expanded for the tuple assignment). 这适用于Python 2和3(其中map()迭代器被扩展用于元组赋值)。

Demo: 演示:

>>> pp=[[0,0] , [-1,5], [2,3], [1,5], [3,6], [4,5], [5,3], [8,-2], [4, -4], [2, -5]]
>>> ppx, ppy = zip(*pp)
>>> ppx
(0, -1, 2, 1, 3, 4, 5, 8, 4, 2)
>>> ppy
(0, 5, 3, 5, 6, 5, 3, -2, -4, -5)
>>> ppx, ppy = map(list, zip(*pp))
>>> ppx
[0, -1, 2, 1, 3, 4, 5, 8, 4, 2]
>>> ppy
[0, 5, 3, 5, 6, 5, 3, -2, -4, -5]

I think that list comprehensions is the most straightforward way: 我认为列表推导是最直接的方式:

xs = [p[0] for p in pp]
ys = [p[1] for p in pp]

Use list comprehensions: 使用列表推导:

pp=[[0,0] , [-1,5], [2,3], [1,5], [3,6], [4,5], [5,3], [8,-2], [4, -4], [2, -5]]
ppx=[a[0] for a in pp]
ppy=[a[1] for a in pp]

More on list comprehensions in the Python docs: http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions 有关Python文档中列表推导的更多信息: http//docs.python.org/2/tutorial/datastructures.html#list-comprehensions

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

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