将2个列表添加到元组列表中

时间:2013-01-26 14:52:21

标签: python

我有一个像这样的列表

[(12,3,1),(12,3,5)]

和另外两个清单

 [4,2]

['A','B'] 

我想将这些添加到第一个列表

[(12,3,4,'A',1),(12,3,2,'B',5)

他们必须处于这个位置,因为我打算删除1中作为元组中最后一个值的那些

2 个答案:

答案 0 :(得分:3)

看,这是一些魔术:

ts = [(12, 3, 1), (12, 3, 5)]
l1 = [4, 2]
l2 = ['A', 'B'] 
[t[:-1] + to_insert + t[-1:] for t, to_insert in zip(ts, zip(l1, l2))]
>> [(12, 3, 4, 'A', 1), (12, 3, 2, 'B', 5)]

答案 1 :(得分:1)

def submerge(d, e, f):
    for g in d[:-1]:
        yield g
    yield e
    yield f
    yield d[-1] # if you want to remove the last element just remove this line

def merge(a, b, c):
    for d, e, f in zip(a, b, c):
        yield tuple(submerge(d, e, f))

a = [(12,3,1),(12,3,5)]
b = [4,2]
c = ['A','B'] 

print list(merge(a, b, c))