2

如果我有这样的列表,如何将来自不同列表的两个项目连接在一起:

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

3 回答 3

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

于 2013-03-07T13:43:30.560 回答
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')]
于 2013-03-07T13:46:16.157 回答
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)
于 2013-03-07T14:08:18.310 回答