简体   繁体   English

Python:从列表数据结构列表中创建元组的每个组合

[英]Python: Create Every Combination of Tuples from a List of Lists Data Structure

Is there a way to create all possible combinations of a list of lists in tuple form without resorting to nested for loops?有没有办法以元组形式创建列表列表的所有可能组合,而无需使用嵌套的 for 循环?

I have the following variable:我有以下变量:

test_list = [['hugs'], ['yelling', 'fighting', 'kicking'], ['love', 'care']]

I want to create the following output but without using nested for loops:我想创建以下 output 但不使用嵌套的 for 循环: 在此处输入图像描述

Is there a way to do this?有没有办法做到这一点? I'd prefer not to have to import a library if possible.如果可能的话,我宁愿不必导入库。

this may help这可能会有所帮助

import itertools导入迭代工具

test_list = [['hugs'], ['yelling', 'fighting', 'kicking'], ['love', 'care']]
mylist = itertools.product(test_list, repeat=2)
print(list(mylist))

result: [(['hugs'], ['hugs']), (['hugs'], ['yelling', 'fighting', 'kicking']), (['hugs'], ['love', 'care']), (['yelling', 'fighting', 'kicking'], ['hugs']), (['yelling', 'fighting', 'kicking'], ['yelling', 'fighting', 'kicking']), (['yelling', 'fighting', 'kicking'], ['love', 'care']), (['love', 'care'], ['hugs']), (['love', 'care'], ['yelling', 'fighting', 'kicking']), (['love', 'care'], ['love', 'care'])]结果:[(['拥抱'],['拥抱']),(['拥抱'],['大喊','战斗','踢']),(['拥抱'],['爱' , 'care']), (['yelling', 'fighting', 'kicking'], ['hugs']), (['yelling', 'fighting', 'kicking'], ['yelling', '战斗','踢']),(['大喊','战斗','踢'],['爱','关心']),(['爱','关心'],['拥抱' ]), (['love', 'care'], ['yelling', 'fighting', 'kicking']), (['love', 'care'], ['love', 'care']) ]

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

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