如果我有这样的列表,如何连接不同列表中的两个项目:
data_list = [['Toys', 'Communications', 'Leather'], ['Teddy', 'Mobile', 'Hand'], ['bear', 'phone', 'bag']]
我使用zip函数将它们转换为这样的元组:
data_tupled_list = zip(*data_list)
结果如下:
[('Toys', 'Teddy', 'bear'),
('Communications', 'Mobile', 'phone'),
('Leather', 'Hand', 'bag')]
我想要一个这样的列表:
[('Toys', 'Teddybear'),
('Communications', 'Mobilephone'),
('Leather', 'Handbag')]
答案 0 :(得分:6)
你大部分时间都在那里:
data_tupled_list = [(x[0],x[1]+x[2]) for x in zip(*data_list)]
如果你解开元组,可能会更漂亮一点:
data_tupled_list = [(a,b+c) for a,b,c in zip(*data_list)]
如果你能给a
,b
和c
更有意义的名字,肯定会更漂亮。
答案 1 :(得分:1)
有一种很好的方法可以在Python3中编写它
>>> data_list = [['Toys', 'Communications', 'Leather'], ['Teddy', 'Mobile', 'Hand'], ['bear', 'phone', 'bag']]
>>> [(x, ''.join(args)) for x, *args in zip(*data_list)]
[('Toys', 'Teddybear'), ('Communications', 'Mobilephone'), ('Leather', 'Handbag')]
答案 2 :(得分:0)
我分两部分进行操作;你真的想做以下事情:
data_list = [['Toys', 'Communications', 'Leather'], ['Teddy', 'Mobile', 'Hand'], ['bear', 'phone', 'bag']]
groups = data_list[0]
predicates = data_list[1]
suffixes = data_list[2]
combined = [ ''.join((pred, suff)) for pred, suff in zip(predicates, suffixes)]
finalresult = zip(groups, combined)