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)

これは、 の各リストの長さが 2 または 3 のみであることを前提としていますcoords。それが異なる場合、これは機能しません。ただし、リストが座標であることを考えると、問題ないはずです。

于 2012-12-12T19:54:03.033 に答える
0

リストのリストを 1 レベルだけ平らにしたい場合、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 に答える