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

时间:2018-09-17 14:33:37

标签: python-2.7 list nested converters

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

[[(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

没有一个能解决我的问题

1 个答案:

答案 0 :(得分: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 = [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]