views:

87

answers:

4

I've got a list like [(1, 2), (1, 8), (2, 3), (2, 7), (2, 8), (2, 9), (3, 1), (3, 2), (3, 5), (3, 6), (3, 7), (3, 7), (3, 9)]

I want to make it looks like [('1',' ', '2', '8'), ('2', ' ', '3', '7', '8', '9'), ('3', " ", '2', '5', '6', '7', '7', '9')]

How can I code this loop? Really tried times, and nothing came up. Please help~~

+2  A: 

Step 1. Convert the list to a dictionary. Each element is a list of values with a common key. (Hint: The key is the first value of each pair)

Step 2. Now format each dictionary as key, space, value list.

S.Lott
Please show me piece of the code since i'm new to python, only 1 day till now. Thank you so much.
@user469652: Please do your own homework, or you'll always be new to Python.
S.Lott
+2  A: 

Not exactly what you asked for, but maybe easier to work with?

>>> from itertools import groupby
>>> L = [(1, 2), (1, 8), (2, 3), (2, 7), (2, 8), (2, 9), (3, 1), (3, 2), (3, 5), (3, 6), (3, 7), (3, 7), (3, 9)]
>>> for key, group in groupby(L, lambda x: x[0]):
...     print key, list(group)
... 
1 [(1, 2), (1, 8)]
2 [(2, 3), (2, 7), (2, 8), (2, 9)]
3 [(3, 1), (3, 2), (3, 5), (3, 6), (3, 7), (3, 7), (3, 9)]

Link to documentation.

Edit:
I suppose something like this is more what you're asking for:

>>> d = {}
>>> for key, group in groupby(L, lambda x: x[0]):
...     d[key] = [i[1] for i in group]
... 
>>> d
{1: [2, 8], 2: [3, 7, 8, 9], 3: [1, 2, 5, 6, 7, 7, 9]}

If you absolutely want the key to be a string, you can code it this way:

d[str(key)] = [i[1] for i in group]
Adam Bernier
Could we combine all the items into one single list []?
We need to get rid of the same number in every first of tuple either.
+1 for using groupby :)
Tumbleweed
A: 
a = [(1, 2), (1, 8), (2, 3), (2, 7), (2, 8), (2, 9), (3, 1), (3, 2), (3, 5), (3, 6),  (3, 7), (3, 7), (3, 9)]

x1=None  # here we keep track of the last x we saw
ys=None  # here we keep track of all ys we've seen for this x1

result = [] 

for x,y in a:
    if x != x1:  # this is an x we haven't seen before
        if ys:   # do we have results for the last x?
            result.append( ys ) 
        ys = [ x, '', y ] # initialize the next set of results
        x1 = x
    else:
        ys.append( y ) # add this to the results we are buliding

if ys:
    result.append( ys )  # add the last set of results

print result
stew
-1: Doing someone's homework for them. DO you want their grades, also? Credit for completing the course?
S.Lott
+2  A: 
from collections import defaultdict

s = [
    (1,2),(1,8),
    (2,3),(2,7),(2,8),(2,9),
    (3,1),(3,2),(3,5),(3,6),(3,7),(3,7),(3,9)
    ]

D = defaultdict(list)
for a,b in s:
    D[a].append(b)

L = []
for k in sorted(D.keys()):
    e = [str(k),'']
    e.extend(map(str,D[k]))
    L.append(tuple(e))

print L

Output:

[('1', '', '2', '8'), ('2', '', '3', '7', '8', '9'), ('3', '', '1', '2', '5', '6', '7', '7', '9')]

You've got to explain how it works to your teacher ;^)

Mark Tolonen