简体   繁体   English

将任意数量的列表元素连接到一个字符串列表python

[英]Join elements of an arbitrary number of lists into one list of strings python

I want to join the elements of two lists into one list and add some characters, like so: 我想将两个列表的元素合并到一个列表中,并添加一些字符,如下所示:

list_1 = ['some1','some2','some3']
list_2 = ['thing1','thing2','thing3']

joined_list = ['some1_thing1', 'some2_thing2', 'some3_thing3']

however i don't know in advance how many lists I will have to do this for, ie I want to do this for an arbitrary number of lists 但是我事先不知道我要为多少个列表做准备,即我想为任意数量的列表做这个准备

Also, I currently receive a list in the following form: 另外,我目前收到以下形式的列表:

list_A = [('some1','thing1'),('some2','thing2'),('some3','thing3')]

so I split it up into lists like so: 所以我将其分成如下列表:

list_B = [i for i in zip(*list_A)]

I do this because sometimes I have an int instead of a string 我这样做是因为有时我有一个int而不是一个字符串

list_A = [('some1','thing1',32),('some1','thing1',42),('some2','thing3', 52)] 

so I can do this after 所以我以后可以做

list_C = [list(map(str,list_B[i])) for i in range(0,len(list_B)]

and basically list_1 and list_2 are the elements of list_C . 和基本上list_1list_2是的元素list_C

So is there a more efficient way to do all this ? 那么,有没有更有效的方法来完成所有这些工作?

Try this if you are using python>=3.6: 如果您使用的是python> = 3.6,请尝试以下操作:

[f'{i}_{j}' for i,j in zip(list_1, list_2)]

If you using python3.5, you can do this: 如果您使用python3.5,则可以执行以下操作:

 ['{}_{}'.format(i,j) for i,j in zip(list_1, list_2)]

also you can use this if you don't want to use formatted string: 如果您不想使用格式化的字符串,也可以使用它:

['_'.join([i,j]) for i,j in zip(list_1, list_2)]

You can join function like this on the base list_A , itself, no need to split it for probable int values: 您可以在基本list_A本身上join函数,无需将其split为可能的int值:

list_A = [('some1','thing1',32),('some1','thing1',42), ('some2','thing3', 52)] 
["_".join(map(str, i)) for i in list_A]

Output: 输出:

['some1_thing1_32', 'some1_thing1_42', 'some2_thing3_52']

Update: 更新:

For you requirement, where you want to ignore last element for last tuple in your list_A , need to add if-else condition inside the list-comprehension as below: 根据您的要求,要在list_A忽略最后一个tuple最后一个元素,需要在list-comprehension内部添加if-else条件,如下所示:

["_".join(map(str, i)) if list_A.index(i) != len(list_A)-1 else "_".join(map(str, i[:-1])) for i in list_A  ]

Updated Output: 更新的输出:

['some1_thing1_32', 'some1_thing1_42', 'some2_thing3']

为了忽略list_A中每个元组的最后一个元素,我发现这是最快的方法:

["_".join(map(str, i)) for i in [x[:-1] for x in list_A] ]

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

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