简体   繁体   English

要元组的单独列表列表

[英]Separate list of lists to tuple

Input    : [['1538', '1'], [False], [True], ['firm']]
Output : [('1538', False, True, 'firm'),
          ('1', False, True, 'firm')]

lzip is giving only the first row lzip 只给出第一行

In [91]: lzip(*[['1538', '1'], [False], [True], ['firm']])
Out[91]: [('1538', False, True, 'firm')]

Also it expects all args to be an iterable.此外,它希望所有 args 都是可迭代的。 I wanted this to handle even if the input is like, [['1538', '1'], False, True, 'firm']我希望即使输入像[['1538', '1'], False, True, 'firm']

What is the easy way to do this有什么简单的方法可以做到这一点

You can use itertools.product您可以使用itertools.product

from itertools import product
list(product(*[['1538', '1'], [False], [True], ['firm']]))
#[('1538', False, True, 'firm'), ('1', False, True, 'firm')]

Building upon ExplodingGayFish's answer , if you want to be able to handle the second case as well:ExplodingGayFish 的回答为基础,如果您也希望能够处理第二种情况:

from itertools import product

Input = [['1538', '1'], [False], [True], ['firm']]
Input2 = [['1538', '1'], False, True, 'firm']

def sep(iterable):
    new_iter = (item if isinstance(item,list) else [item] for item in iterable)
    return list(product(*new_iter))

print(sep(Input))
print(sep(Input2))

Output:输出:

[('1538', False, True, 'firm'), ('1', False, True, 'firm')]
[('1538', False, True, 'firm'), ('1', False, True, 'firm')]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM