如何用Python连接两个来自不同列表的项?

2 投票
3 回答
1784 浏览
提问于 2025-04-17 18:16

如果我有两个不同的列表,想把它们的两个元素合并在一起,应该怎么做呢?比如说,我有这样的列表:

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')]

3 个回答

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)
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')]
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)]

而且如果你能给 abc 起一些更有意义的名字,那就绝对会更好看。

撰写回答