[英]how can I walk through a list of list of (x,y) in python
How can I walk through a list of list of (x,y)
in python? 如何在python中浏览
(x,y)
列表列表?
I have a data structure like this in python, which is a list of a list of a (x,y)
我在python中有一个像这样的数据结构,它是
(x,y)
列表的列表
coords = [
[[490, 185] , [490, 254], [490, 312] ], # 0
[[420, 135] , [492, 234], [491, 313], [325, 352] ], # 1
]
I want to walk through the list and get x, y
of each set: 我想遍历列表并获取每组的
x, y
:
# where count goes from 0 to 1
a_set_coord[] = coords[count]
for (tx, ty) in a_set_coord:
print "tx = " + tx + " ty = " + ty
But I get error: 但是我得到了错误:
SyntaxError: ("no viable alternative at input ']'"
How can I fix this? 我怎样才能解决这个问题?
Remove the brackets after a_set_coord
: 移除
a_set_coord
之后的括号:
a_set_coord = coords[count]
Also, the print
statement tries to concatenate strings and ints. 同样,
print
语句尝试连接字符串和整数。 Change it to: 更改为:
print "tx = %d ty = %d" % (tx, ty)
If you just want to flatten your list of lists by one level, itertools.chain
or itertools.chain.from_iterable
could be very helpful: 如果您只想将列表列表平整一级,
itertools.chain
或itertools.chain.from_iterable
可能会非常有用:
>>> coords = [
... [[490, 185] , [490, 254], [490, 312] ], # 0
... [[420, 135] , [492, 234], [491, 313], [325, 352] ], # 1
... ]
>>> import itertools as it
>>> for x,y in it.chain.from_iterable(coords):
... print ('tx = {0} ty = {1}'.format(x,y))
...
tx = 490 ty = 185
tx = 490 ty = 254
tx = 490 ty = 312
tx = 420 ty = 135
tx = 492 ty = 234
tx = 491 ty = 313
tx = 325 ty = 352
Use a simple for
loop. 使用简单的
for
循环。
for i in coords:
x = i[0]
y = i[1]
if len(i) == 3: z = i[2] # if there is a 'z' coordinate for a 3D graph.
print(x, y, z)
This assumes that each list in coords
is only of length 2 or 3. If it is different, this will not work. 这假定
coords
中的每个列表的长度仅为2或3。如果长度不同,则此列表将不起作用。 However, considering the lists are coordinates, it should be fine. 但是,考虑到列表是坐标,应该没问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.