【问题标题】:Convert mixed nested list (mixed tuples and lists of 2 dimension) to 1 dim list将混合嵌套列表(混合元组和二维列表)转换为 1 个暗淡列表
【发布时间】:2018-09-17 14:33:36
【问题描述】:

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

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

他们都没有解决我的问题

【问题讨论】:

  • 是否可以有更高级别的嵌套列表,例如[[[(0, 500)], [[(456, 90), [56, 85]]]]]

标签: python-2.7 list nested converters


【解决方案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]

【讨论】:

  • 非常感谢!同时,我找到了一种解决方法,在其中我编辑了给我列表的函数。我对其进行了更改,以便仅获得列表(不再有元组),然后将其展平。但是,您的帖子的输出看起来像这样 [[0, 500], [755, 1800], [2600], [2900], [4900], [9000], [11000, 17200]]。所以 [2600,2900] 的配对不如 [4900,9000] 好。
  • 我明白了。请注意,在速度和内存方面,使用列表理解更好。不过,我很高兴您找到了解决方法!
猜你喜欢
  • 2018-02-03
  • 2014-12-30
  • 1970-01-01
  • 2021-04-15
  • 1970-01-01
  • 1970-01-01
  • 2018-12-26
  • 2017-09-11
  • 2015-11-20
相关资源
最近更新 更多