我有一个像这样的清单 [(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')]
如何编写此循环代码?真的很受欢迎,没有任何事情发生。请帮忙~~
答案 0 :(得分:2)
步骤1.将列表转换为字典。每个元素都是一个带有公共密钥的值列表。 (提示:关键是每对的第一个值)
步骤2.现在将每个字典格式化为键,空格,值列表。
答案 1 :(得分: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 :(得分:2)
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
[('1', '', '2', '8'), ('2', '', '3', '7', '8', '9'), ('3', '', '1', '2', '5', '6', '7', '7', '9')]
你必须向老师解释它是如何运作的; ^)
答案 3 :(得分: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