通过数组的数组循环以创建模型

2024-10-03 15:24:27 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的数组

var arrOfArr = [['the', 'man'],
['at'],
['in']]

在这个简单的例子中,只有

the at in and  man at in

在这个数组中

var arrofArr = [['the', 'man'],
['at'],['of']
['in']]

就在这里

the at in, the of in
and
man at in, man of in

在这种情况下

var myArrOfArr = [['the', 'man'],
['is',  'was', 'at'],
['and', 'of'],
['but', 'not']]

我想以一种特殊的方式循环这个数组,比如

所有可能的组合按向下的顺序排列

the is and but, the is and not, the was and but, the was and not, the at and but, the at and not,
the is of but, the is of not, the was of but, the was of not, the at of but, the at of not,

man is and but..
man is of but.

数组长度可能会有所不同。有人能帮我解决这个复杂的迭代吗

我目前正在nodejs中做这件事,这是一种好的语言,还是python有简单的工具

嗨,nodej能完成同样的任务吗?好吗?请给我一个意见


Tags: andoftheinisvarnot数组
3条回答

itertools.product()是您想要的:

import itertools

myArrOfArr = [['the', 'man'],
['is',  'was', 'at'],
['and', 'of'],
['but', 'not']]

for q in itertools.product(*myArrOfArr):
    print(q)

如果您有任何问题,请留下评论。:-)

你可以用这个

import itertools
myArrOfArr = [['the', 'man'],
['is',  'was', 'at'],
['and', 'of'],
['but', 'not']]

arr = [' '.join(str(y) for y in x) for x in itertools.product(*myArrOfArr)]

print(arr)
#['the is and but', 'the is and not', 'the is of but', 'the is of not', 'the was and but', 'the was and not', 'the was of but', 'the was of not', 'the at and but', 'the at and not', 'the at of but', 'the at of not', 'man is and but', 'man is and not', 'man is of but', 'man is of not', 'man was and but', 'man was and not', 'man was of but', 'man was of not', 'man at and but', 'man at and not', 'man at of but', 'man at of not']
import itertools 
myArrOfArr = [['the', 'man'],['is',  'was', 'at'],['and', 'of'],['but', 'not']]

op = list(itertools.product(*myArrOfArr)) 
print(op)

答复

[('the', 'is', 'and', 'but'), ('the', 'is', 'and', 'not'), ('the', 'is', 'of', 'but'), ('the', 'is', 'of', 'not'), ('the', 'was', 'and', 'but'), ('the', 'was', 'and', 'not'), ('the', 'was', 'of', 'but'), ('the', 'was', 'of', 'not'), ('the', 'at', 'and', 'but'), ('the', 'at', 'and', 'not'), ('the', 'at', 'of', 'but'), ('the', 'at', 'of', 'not'), ('man', 'is', 'and', 'but'), ('man', 'is', 'and', 'not'), ('man', 'is', 'of', 'but'), ('man', 'is', 'of', 'not'), ('man', 'was', 'and', 'but'), ('man', 'was', 'and', 'not'), ('man', 'was', 'of', 'but'), ('man', 'was', 'of', 'not'), ('man', 'at', 'and', 'but'), ('man', 'at', 'and', 'not'), ('man', 'at', 'of', 'but'), ('man', 'at', 'of', 'not')]

这是参考资料 https://www.geeksforgeeks.org/python-all-possible-permutations-of-n-lists/

相关问题 更多 >