Python 从列表列表创建单个列表
从Python 从列表列表创建单个列表,python,python-2.7,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(',')): ^
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
文件“”,第4行
对于(x.split(',')中的y):
^
SyntaxError:无效语法
当
x.split(',')
返回已解析元素的列表时,在此上下文中,它应该是有效的for循环?您有一个额外的参数。试一试
comb = []
for x in data:
for y in x.split(','):
comb.append(y)
你并不真的需要内环
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']
最佳性能:避免
追加
,扩展
:只需使用两个平面循环进行列表理解:
data = ["1,2","3,4"]
data_flat = [x for c in data for x in c.split(",")]
print(data_flat)
结果:
['1', '2', '3', '4']
你差点就成功了。您在第一个上有的
。似乎拆分后的paren将您弄糊涂了,并使您恢复到另一种编程语言,该语言将paren置于和if
标准中。通过从y的中删除无关的参数,您可以修复它
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']
一行:
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)
拆下外护板对于x.split(',')中的y:
作为替代,您可以使用类似这样的列表理解:comb=[i for x in data for x for i in x.split(',')]
为什么在[x for c in data for x in c.split(“,”)中的“x”前面加上“x”[x for c in data for x in c.split(,”)它是以另一种方式编写的:x是在后面描述的循环中创建的元素。列表理解语法。布鲁诺,宾果注释:)