【问题标题】:map corresponding elements in a nested list映射嵌套列表中的对应元素
【发布时间】:2019-12-05 09:07:53
【问题描述】:

输入:[('1', '100'), (False,), (True,), ('1', '100')] 输出:

[('1', False, True, '1'),
 ('100', False, True, '100')]

但是当我使用 itertools.product 时,它给了我一个完整的交叉产品

In [191]: l
Out[191]: [('1', '100'), (False,), (True,), ('1', '100')]

In [192]: list(itertools.product(*l))
Out[192]: 
[('1', False, True, '1'),
 ('1', False, True, '100'),
 ('100', False, True, '1'),
 ('100', False, True, '100')]

列表中的所有元组大小相等或大小为 1。

我可以通过以下看起来不太好的方法来实现这一点

In [231]: [[l[i][v] if len(l[i]) > v else l[i][0] for i in range(len(l))] for v in range(max(map(len, l)))]
Out[231]: [['1', False, True, '1'], ['100', False, True, '100']]

【问题讨论】:

    标签: python list tuples zip itertools


    【解决方案1】:

    试试这个:

    >>> Input = [('1', '100'), (False,), (True,), ('1', '100')]
    >>> Output = [sum([(i,)]+ Input[1:-1]+ [(i,)],()) for i in Input[-1]]
    >>> Output
    [('1', False, True, '1'), ('100', False, True, '100')]
    

    【讨论】:

      猜你喜欢
      • 2020-11-16
      • 1970-01-01
      • 1970-01-01
      • 2017-05-25
      • 2012-09-07
      • 1970-01-01
      • 1970-01-01
      • 2011-08-07
      • 2015-03-07
      相关资源
      最近更新 更多