我有一个这样的清单:
[(0, 1), (0, 2), (0, 3), (1, 4), (1, 6), (1, 7), (1, 9)]
我需要转换为一个看起来像这样的元组:
[(0, [1, 2, 3]), (1, [4, 6, 7, 9])]
这是我的代码:
friends = open(file_name).read().splitlines()
network = []
friends = [tuple(int(y) for y in x.split(' ')) for x in friends]
return friends
答案 0 :(得分:0)
你可以试试这个:
import itertools
s = [(0, 1), (0, 2), (0, 3), (1, 4), (1, 6), (1, 7), (1, 9)]
final_data = [(a, [i[-1] for i in list(b)]) for a, b in itertools.groupby(sorted(s, key=lambda x:x[0]), key=lambda x:x[0])]
输出:
[(0, [1, 2, 3]), (1, [4, 6, 7, 9])]
答案 1 :(得分:0)
这不是你要求的,但是根据你要找的输出类型,我建议你使用defaultdict,这是超级可读和高效的,
from collections import defaultdict
some_list = [(0, 1), (0, 2), (0, 3), (1, 4), (1, 6), (1, 7), (1, 9)]
d = defaultdict(list)
for k, v in some_list:
d[k].append(v)
<强>输出强>
defaultdict(<class 'list'>, {0: [1, 2, 3], 1: [4, 6, 7, 9]})
答案 2 :(得分:0)
一个'一行'嵌套列表理解,带换行符
tpls = [(0, 1), (0, 2), (0, 3), (1, 4), (1, 6), (1, 7), (1, 9)]
[(k, [tp[1] for tp in tpls if tp[0] == k])
for k in set([*zip(*tpls)][0])]
Out[11]: [(0, [1, 2, 3]), (1, [4, 6, 7, 9])]
[*zip(*tpls)]
是一个'转置'子迭代
给予[(0, 0, 0, 1, 1, 1, 1), (1, 2, 3, 4, 6, 7, 9)]
所以set([*zip(*tpls)][0])
是set((0, 0, 0, 1, 1, 1, 1))
在tpls
{0, 1}
中给出元组第一个位置的唯一项:for k in ...
k
迭代的,将[tp[1] for tp in tpls if tp[0] == k]
提供给结果元组内的列表comp
ggplot(data=predicted, aes(Edu, Wage)) +
geom_line() +
geom_point() +
geom_line(data=satmodel, colour="blue") +
geom_point(data=satmodel, colour="blue")