如何浏览python中的(x,y)
列表?
我在python中有这样的数据结构,它是一个(x,y)
coords = [
[[490, 185] , [490, 254], [490, 312] ], # 0
[[420, 135] , [492, 234], [491, 313], [325, 352] ], # 1
]
我想浏览一下列表并获得每组的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
但我得到错误:
SyntaxError: ("no viable alternative at input ']'"
我该如何解决这个问题?
答案 0 :(得分:3)
删除a_set_coord
之后的括号:
a_set_coord = coords[count]
此外,print
语句尝试连接字符串和整数。将其更改为:
print "tx = %d ty = %d" % (tx, ty)
答案 1 :(得分:0)
如果您只想将列表列表展平一级,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
答案 2 :(得分:0)
使用简单的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)
这假设coords
中的每个列表的长度仅为2或3.如果不同,则不起作用。但是,考虑到列表是坐标,它应该没问题。