2024-04-23 19:40:36 发布
网友
我有这个清单:
list1 = [['a', 'b', 'c', 'd']]
我找到的转换为一个列表的方法:
list1 = [['a', 'b', 'c', 'd']] result = [] for i in range(len(list1)): for j in range(len(list1[i])): result.append(list1[i][j]) print result
结果是:
['a', 'b', 'c', 'd']
还有别的办法吗??你知道吗
如果您只有一个项目,显然list1[0]将起作用。你知道吗
list1[0]
另外,在一般情况下也有类似的问题,例如Making a flat list out of list of lists in Python
这给了包括
sum(list1, [])
只需将列表索引到0:
0
result = list1[0]
演示:
>>> list1 = [['a', 'b', 'c', 'd']] >>> result = list1[0] >>> result ['a', 'b', 'c', 'd'] >>>
对于多个子列表,可以使用^{}:
>>> from itertools import chain >>> list1 = [['a', 'b', 'c', 'd'], ['w', 'x', 'y', 'z']] >>> list(chain.from_iterable(list1)) ['a', 'b', 'c', 'd', 'w', 'x', 'y', 'z'] >>>
如果有多个列表,则可以直接将它们串联在一起:
list1 = [['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h']] result = [] for sublist in list1: result += sublist print result
如果只是一个嵌套列表,iCodez会给出一个更快的答案。你知道吗
如果您只有一个项目,显然
list1[0]
将起作用。你知道吗另外,在一般情况下也有类似的问题,例如Making a flat list out of list of lists in Python
这给了包括
只需将列表索引到
0
:演示:
对于多个子列表,可以使用^{} :
如果有多个列表,则可以直接将它们串联在一起:
如果只是一个嵌套列表,iCodez会给出一个更快的答案。你知道吗
相关问题 更多 >
编程相关推荐