Python,格式化这个列表
我有一个这样的列表:
[(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)]
我想把它变成这样:
[('1',' ', '2', '8'), ('2', ' ', '3', '7', '8', '9'), ('3', " ", '2', '5', '6', '7', '7', '9')]
我该怎么写这个循环呢?我试了很多次,但都没有成功。请帮帮我~~
4 个回答
2
这不是你问的完全一样,但可能更好用一些?
>>> 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)]
编辑:
我想这可能更接近你想要的内容:
>>> 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]}
如果你真的想要键是一个字符串,你可以这样写代码:
d[str(key)] = [i[1] for i in group]
2
第一步:把列表转换成字典。每个元素都是一组有共同键的值的列表。(提示:这个键就是每对值中的第一个值)
第二步:现在把每个字典格式化成“键,空格,值”的形式。
0
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
这段代码的作用是……
首先,它会……然后,它会……接着,它会……最后,它会……
总的来说,这段代码的流程是这样的:……
如果你对某些部分不太明白,可以想象成……
希望这个解释能帮助你更好地理解这段代码!