繁体   English   中英

我如何在python中浏览(x,y)列表列表

[英]how can I walk through a list of list of (x,y) in python

如何在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 ']'"

我怎样才能解决这个问题?

移除a_set_coord之后的括号:

a_set_coord = coords[count]

同样, print语句尝试连接字符串和整数。 更改为:

print "tx = %d ty = %d" % (tx, ty)

如果您只想将列表列表平整一级, itertools.chainitertools.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

使用简单的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。如果长度不同,则此列表将不起作用。 但是,考虑到列表是坐标,应该没问题。

暂无
暂无

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

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