Python 在嵌套列表中映射相应的元素
输入:Python 在嵌套列表中映射相应的元素,python,list,tuples,zip,itertools,Python,List,Tuples,Zip,Itertools,输入:[('1','100'),(假,),(真,),('1','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'
[('1','100'),(假,),(真,),('1','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']]
试试这个:
>>> 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')]
>>> 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')]