将混合嵌套列表(混合元组和2维列表)转换为1个暗淡列表

问题描述 投票:0回答:1

我有一个混合列表,包含带有元组(第二维)的列表,如下所示:

[[(0, 500), (755, 1800)], [2600, 2900], [4900, 9000], [(11000, 17200)]]

列表应该如下所示

[[0, 500], [755, 1800], [2600, 2900], [4900, 9000], [11000, 17200]]

我尝试了map和list()转换函数的调用。

#Try 1: works for just the first element
experiment = map(list,cleanedSeg[0])
#Try 2: gives error int not interabel
experiment = [map(list,elem) for elem in cleanedSeg if isinstance(elem, (tuple, list))]
#Try 3: 
experiment = [list(x for x in xs) for xs in cleanedSeg]

print experiment

他们都没有解决我的问题

python-2.7 list nested converters
1个回答
1
投票
mixlist = [[(0, 500), (755, 1800)], [2600, 2900], [4900, 9000], [(11000, 17200)]]

# [[0, 500], [755, 1800], [2600, 2900], [4900, 9000], [11000, 17200]]
experiment = [list(n) if isinstance(n, tuple) else [n] for sub in mixlist for n in sub]

我在下面尝试了两个版本的列表理解。以上一种和另一种替代方式

experiment = [list(n) if isinstance(n, tuple) else list(n) for sub in mixlist for n in sub]

此表达式给出以下错误:

TypeError: Argument of type 'int' is not iterable. 

这两个表达式之间的区别在于使用list literal,[]和list函数,()。

list_literal = [n] # Gives a list literal [n]
ls = list(n) # Iterate over n's items and produce a list from that.

例如:

>>> n = (1,2,3)
>>> list_literal = [n]
>>> list_literal
[(1, 2, 3)]
>>> n = (1,2,3)
>>> list_literal = list(n)
>>> list_literal
[1, 2, 3]
© www.soinside.com 2019 - 2024. All rights reserved.