简体   繁体   English

从列表列表创建单个列表

[英]Create single list from list of lists

From data = ["1,2","3,4"] I'm attempting to create a list of strings : ["1","2","3","4"] data = ["1,2","3,4"]我试图创建一个字符串列表: ["1","2","3","4"]

Trying this code : 试试这个代码:

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

returns : 返回:

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

As x.split(',') return a list of the parsed elements , in this context it should be a valid for loop ? 由于x.split(',')返回已解析元素的列表,在这种情况下,它应该是有效的for循环?

most performant: avoid append , extend : just do a list comprehension with 2 flat loops: 最高效的:避免appendextend :只对两个平面循环进行列表理解:

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

print(data_flat)

result: 结果:

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

You have an extra paranthesis. 您有一个额外的习惯。 Try 尝试

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

You don't really need the inner loop. 您实际上不需要内部循环。

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

You almost had it. 你差点就吃了。 You had the for right on the first one. 你有for权放在了第一位。 It seems that the parens after the split confused you and made you revert to another programming language that puts parens around for and if criteria. split后的parens似乎使您感到困惑,并使您恢复为另一种编程语言,该parang将forif准则置于parens中。 By removing the extraneous parens from the for y , you can fix it. 通过从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']

A one liner: 一个班轮:

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

Output: 输出:

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

But your code is absolutely fine.The problem was that extra brackets you gave in your for loop: 但是您的代码绝对正确,问题在于您在for循环中添加了多余的括号:

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

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

print(comb)

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

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