tags:

views:

69

answers:

2

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

For 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.

+3  A: 
>>> 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.

Roger Pate
This would work for that exact example, but for grouping 2 long lists together that would be very space- and time-consuming.
Jam
@Jam: So then make them generator expressions instead.
Ignacio Vazquez-Abrams
@Jam: You can unwind the LC directly into a for loop (notice how similar the syntax will be) to avoid storing all of it at once. Or use a generator.
Roger Pate
Thank you so much. That last one is what I was looking for. I was indenting the second 'print' too much.
Jam
@Jam: It usually helps to tell us about what you've tried (but don't neglect to describe what you really want to do, too).
Roger Pate
+1  A: 

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?

wich