好的,所以我最终会得到很多像这样的元组列表。
l1 = [('A', 1), ('B', 2), ('C', 3), ('D', 4), ('E', 5)]
l2 = [('A', 1), ('C', 2), ('F', 8), ('D', 15), ('X',21)]
l3 = [('C', 1), ('F', 4), ('R', 16), ('D', 19), ('Z', 31)]
每个列表中的位置已按数字排序。
我需要做的是构建一个元组列表,它将所有列表中的信息组合成这样的格式。
final_list = [('A', 1, 1, 0), ('B', 2, 0, 0), ('C', 3, 2, 1), ('D', 4, 15, 19), ('E', 5, 0, 0), ('F', 0, 8, 4), ('X', 0, 21, 0), ('R', 0, 0, 16), ('Z', 0, 0, 31)]
最重要的部分是元组本身按名称,列表1,列表2,列表3等顺序排列,当列表中没有字母/名称时,列表位置为零。
这是否太复杂了,我是否已将自己编入一个洞?
答案 0 :(得分:0)
您可以分两步完成此操作:
首先构造一个dict,然后构造final_list
from collections import defaultdict
li = [l1, l2, l3, ...]
temp_dict = defaultdict(tuple)
for l in li:
for e in l:
temp_dict[e[0]] += (e[1],)
# Got {'A': (1, 1, 0), 'B': (2, 0, 0), ... }
final_list = [(key, ) + temp_dict[key] for key in temp_dict]
在REPL中尝试过:
>>> l1 = [('A', 1), ('B', 2), ('C', 3), ('D', 4), ('E', 5)]
>>> l2 = [('A', 1), ('C', 2), ('F', 8), ('D', 15), ('X',21)]
>>> l3 = [('C', 1), ('F', 4), ('R', 16), ('D', 19), ('Z', 31)]
>>> from collections import defaultdict
>>> li = [l1, l2, l3,]
>>> temp_dict = defaultdict(tuple)
>>> for l in li:
... for e in l:
... temp_dict[e[0]] += (e[1],)
...
>>> temp_dict
defaultdict(<type 'tuple'>, {'A': (1, 1), 'C': (3, 2, 1), 'B': (2,), 'E': (5,), 'D': (4, 15, 19), 'F': (8, 4), 'R': (16,), 'X': (21,), 'Z': (31,)})
>>> final_list = [(key, ) + temp_dict[key] for key in temp_dict]
>>> final_list
[('A', 1, 1), ('C', 3, 2, 1), ('B', 2), ('E', 5), ('D', 4, 15, 19), ('F', 8, 4), ('R', 16), ('X', 21), ('Z', 31)]
答案 1 :(得分:0)
不,它并不太复杂,尽管您可能希望考虑使用字母键入的列表(或元组)的字典。 OTOH,你当前的设置比dict使用更少的内存。
#! /usr/bin/env python
l1 = [('A', 1), ('B', 2), ('C', 3), ('D', 4), ('E', 5)]
l2 = [('A', 1), ('C', 2), ('F', 8), ('D', 15), ('X',21)]
l3 = [('C', 1), ('F', 4), ('R', 16), ('D', 19), ('Z', 31)]
def main():
dlist = [dict(u) for u in (l1, l2, l3)]
keys = sorted(set(sum([d.keys() for d in dlist], [])))
final = [(key,) + tuple([d.get(key, 0) for d in dlist]) for key in keys]
for row in final:
print row
if __name__ == '__main__':
main()
答案 2 :(得分:0)
再次更新! 功能更加紧凑。
*
l1 = [('A', 1, 3), ('B', 2, 5), ('C', 3, 16), ('D', 4, 19), ('E', 5, 20)];
l2 = [('A', 1), ('C', 2), ('F', 8), ('D', 15), ('X',21)];
l3 = [('C', 1), ('F', 4), ('R', 16), ('D', 19), ('Z', 31)]
for k in l1,l2,l3:
# 'dummy to keep track of tuple size'
k.append(('dummy',len(k[0][1:])))
dict_lx = [ dict(map(lambda x: (x[0], x[1:]), l)) for l in l1,l2,l3 ]
sorted_keys = sorted(set(reduce(lambda x,y : x + y.keys(), dict_lx, [])))
final = map(lambda key: tuple(
[key] + reduce(lambda x,y: x + list(y.get(key, y.get('dummy')[0]*[0])), dict_lx, [])), sorted_keys)
final = filter(lambda x: x[0] != 'dummy', final)
print final
#[('A', 1, 3, 1, 0), ('B', 2, 5, 0, 0), ('C', 3, 16, 2, 1), ('D', 4, 19, 15, 19), ('E', 5, 20, 0, 0), ('F', 0, 0, 8, 4), ('R', 0, 0, 0, 16), ('X', 0, 0, 21, 0), ('Z', 0, 0, 0, 31)]
*