将混合嵌套列表(混合元组和二维列表)转换为 1 个暗淡列表
Convert mixed nested list (mixed tuples and lists of 2 dimension) to 1 dim list
我有一个混合列表,包含带有元组的列表(第二维),如下所示:
[[(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
none 确实解决了我的问题
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]
我有一个混合列表,包含带有元组的列表(第二维),如下所示:
[[(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
none 确实解决了我的问题
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]