简体   繁体   English

如何使用python连接不同列表中的两个项目?

[英]How to concatenate two items from different lists using python?

How can I concatenate two items from different lists, together, if I have lists like this: 如果我有这样的列表,如何连接不同列表中的两个项目:

data_list = [['Toys', 'Communications', 'Leather'], ['Teddy', 'Mobile', 'Hand'], ['bear', 'phone', 'bag']]

I have used zip function to convert them into tuples like this: 我已经使用zip函数将它们转换为元组,如下所示:

data_tupled_list = zip(*data_list)

which results like this: 结果如下:

[('Toys', 'Teddy', 'bear'),
 ('Communications', 'Mobile', 'phone'),
 ('Leather', 'Hand', 'bag')]

I want a list like this: 我想要一个这样的列表:

[('Toys', 'Teddybear'),
 ('Communications', 'Mobilephone'),
 ('Leather', 'Handbag')]

You're most of the way there: 您已到达那里:

data_tupled_list = [(x[0],x[1]+x[2]) for x in zip(*data_list)]

It might be a little more pretty if you unpack the tuple: 如果你拆开元组,它可能会更漂亮一点:

data_tupled_list = [(a,b+c) for a,b,c in zip(*data_list)]

And it would definitely be prettier if you could give a , b and c more meaningful names. 如果你能给abc更有意义的名字肯定会更漂亮。

There is a nice way to write this in Python3 有一个不错的方法可以用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')]

I'd operate on it in two parts; 我将分两部分对其进行操作; you really want to do the following: 你真的想做以下事情:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM