从列表列表中创建单个列表

时间:2017-01-10 17:01:29

标签: python python-2.7

data = ["1,2","3,4"]我尝试创建字符串列表:["1","2","3","4"]

尝试此代码:

comb = []
for x in data:
    for(y in x.split(',')):
        comb.append(y)

返回:

  File "<ipython-input-46-20897dcf51a1>", line 4
    for(y in x.split(',')):
                          ^
SyntaxError: invalid syntax

x.split(',')返回已解析元素的列表时,在此上下文中它应该是一个有效的for循环?

5 个答案:

答案 0 :(得分:3)

性能最佳:避免appendextend:只需使用2个扁平循环执行列表理解:

data = ["1,2","3,4"]
data_flat = [x for c in data for x in c.split(",")]

print(data_flat)

结果:

['1', '2', '3', '4']

答案 1 :(得分:0)

你有一个额外的paranthesis。尝试

comb = []
for x in data:
    for y in x.split(','):
        comb.append(y)

答案 2 :(得分:0)

你真的不需要内循环。

In [1]: data = ["1,2","3,4"]

In [2]: comb=list()

In [3]: for d in data:
   ...:     comb.extend(d.split(","))
   ...:

In [4]: comb
Out[4]: ['1', '2', '3', '4']

答案 3 :(得分:0)

你几乎拥有它。你在第一个上有for权利。似乎split之后的parens让你感到困惑,并让你恢复到另一种编程语言,这种语言将问题置于forif条件之下。通过从for y删除无关的parens,您可以修复它。

In [22]: data = ["1,2","3,4"]
    ...:
    ...: comb = []
    ...:
    ...: for x in data:
    ...:     for y in x.split(','):
    ...:         comb.append(y)
    ...:

In [23]: comb
Out[23]: ['1', '2', '3', '4']

答案 4 :(得分:0)

一个班轮:

print([item for sublist in ["1,2","3,4"] for item in sublist.split(',')])

输出:

['1', '2', '3', '4']

但是你的代码绝对没问题。问题是你在for循环中给出了额外的括号:

data = ["1,2","3,4"]

comb = []
for x in data:
    for y in x.split(','): #corrected
        comb.append(y)

print(comb)