加入列表中的列表?

时间:2016-07-25 18:50:25

标签: python list join

我试图在python的列表中加入一些列表这里是我正在做的一个例子(列表在实际代码中要大得多):

import itertools

listenv = ["IN","VC","VS"]
listsize = ["U17-1","U17-2"]

listevnsize = list(itertools.product(listenv, listsize,))

print listevnsize
#This results in [('IN', 'U17-1'), ('IN', 'U17-2'), ('VC', 'U17-1'), ('VC', 'U17-2'), ('VS', 'U17-1'), ('VS', 'U17-2')]

我现在要做的是将内部列表与 - 例如我希望结果结合起来:

[('IN-U17-1'), ('IN-U17-2'), ('VC-U17-1'), ('VC-U17-2'), ('VS-U17-1'), ('VS-U17-2')]

所以换句话说我想加入内部列表,但是当我尝试使用时:

listevnsizejoined = '-'.join(map(str,listevnsizezip))

正如另一个问题所示,这是将所有外部列表连接成一个大字符串,如下所示:

(('IN', 'U17-1'),)-(('IN', 'U17-2'),)-(('VC', 'U17-1'),)-(('VC', 'U17-2'),)-(('VS', 'U17-1'),)

最终解决方案:

import itertools

listenv = ["IN","VC","VS","VX","RH","HT","DP","AD","PT","PTRH","WP","WPRH","CYVX","HM"];
listsize = ["U17-1","U17-2"];
listseventeenGR = ["17P:3","17P:4","17P:5.5","17P:7","17P:10","17P:16","17P:22","17P:28","17P:40","17P:49","17P:55","17P:70","17P:100"]


listevnsize = list(itertools.product(listenv, listsize,))

listenvsizejoined = []

for x in listevnsize:
    listenvsizejoined.append('-'.join(i for i in x))

print listenvsizejoined

这是在所有组合中组合两个列表,然后用短划线连接这些内部列表的最终解决方案。

3 个答案:

答案 0 :(得分:0)

这样可以,只需使用zip

new_list = []
for i,j in zip(listenv, listsize):
    new_list.append(('{0}-{1}').format(i,j))

答案 1 :(得分:0)

使用str.join

S.join(iterable) -> string

Return a string which is the concatenation of the strings in the
iterable.  The separator between elements is S.

l = []

for x in listevnsize:
    l.append('-'.join(i for i in x))

答案 2 :(得分:0)

listenvsize = ["{}-{}".format(x,y) for x in listenv for y in listsize]

结果不会是元组列表,因为元组中只有一个元素。