开发者

Group and stack tuples

I'm just starting with Python, and I can't figure out how to group tuples.

F开发者_JAVA技巧or instance, I have tuple1=("A", "B", "C") and tuple2=("1","2","3"). I want to combine these into a list, grouped by the first tuple. I want it to appear stacked, as in A1 A2 A3 on one line, and B1 B2 B3 on the next line.

I can make them print concatenated, but I can't figure out how to stack them nicely.


>>> t1 = ("A", "B", "C")
>>> t2 = ("1", "2", "3")
>>> [x + y for x in t1 for y in t2]
['A1', 'A2', 'A3', 'B1', 'B2', 'B3', 'C1', 'C2', 'C3']
>>> [[x + y for y in t2] for x in t1]
[['A1', 'A2', 'A3'], ['B1', 'B2', 'B3'], ['C1', 'C2', 'C3']]
>>> x = _  # assign x to the last value
>>> for row in x:
...   print " ".join(row)
... 
A1 A2 A3
B1 B2 B3
C1 C2 C3
>>> for x in t1:
...   for y in t2:
...     print x + y,  # notice the comma, special print-statement syntax
...   print
A1 A2 A3
B1 B2 B3
C1 C2 C3

The [..] are used here as list comprehensions.


I'm not exacly sure what your problem is precisely, but do you mean the following?

for x in ("A", "B", "C"):
    print [x + y for y in ("1", "2", "3")]

What do you mean by stacked?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜