0

如何浏览(x,y)python 中的列表列表?

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

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

4

3 回答 3

3

删除之后的括号a_set_coord

a_set_coord = coords[count]

此外,该print语句尝试连接字符串和整数。将其更改为:

print "tx = %d ty = %d" % (tx, ty)
于 2012-12-12T19:17:31.837 回答
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。如果不同,这将不起作用。但是,考虑到列表是坐标,应该没问题。

于 2012-12-12T19:54:03.033 回答
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
于 2012-12-12T19:22:00.520 回答