python 从元素创建不同的数组

vxqlmq5t  于 2023-02-15  发布在  Python
关注(0)|答案(1)|浏览(107)
obj = [
   {name: "obj1"},
   {name: "obj2"},
   {name: "obj3"}
]

我有这些元素,我想用这些元素创建不同的数组,比如第一个数组10x obj1,第二个数组9x obj1和1 obj2,第三个数组8x obj1和2x obj2,就像这样,我需要每种可能性:

arr1 = [
{name: "obj1"},
{name: "obj1"},
{name: "obj1"},
{name: "obj1"},
{name: "obj1"},
{name: "obj1"},
{name: "obj1"},
{name: "obj1"},
{name: "obj1"},
{name: "obj1"}
]

arr2 = [
{name: "obj1"},
{name: "obj1"},
{name: "obj1"},
{name: "obj1"},
{name: "obj1"},
{name: "obj1"},
{name: "obj1"},
{name: "obj1"},
{name: "obj1"},
{name: "obj2"}
]

arr3 = [
{name: "obj1"},
{name: "obj1"},
{name: "obj1"},
{name: "obj1"},
{name: "obj1"},
{name: "obj1"},
{name: "obj1"},
{name: "obj1"},
{name: "obj2"},
{name: "obj2"}
]
arr4 = [
{name: "obj1"},
{name: "obj1"},
{name: "obj1"},
{name: "obj1"},
{name: "obj1"},
{name: "obj1"},
{name: "obj1"},
{name: "obj2"},
{name: "obj2"},
{name: "obj2"}
]
.
.
.

我怎样才能做到呢

o8x7eapl

o8x7eapl1#

下面的脚本可以正常工作。

obj = [
   {'name': 'obj1'},
   {'name': 'obj2'},
   {'name': 'obj3'}
]

results = []
for idx_obj1 in range(0, 11):
    for idx_obj2 in range(0, 11 - idx_obj1):
        idx_obj3 = 10 - idx_obj1 - idx_obj2
        arr = [{'name': 'obj1'} for i in range(idx_obj1)] + [{'name': 'obj2'} for i in range(idx_obj2)] + [{'name': 'obj3'} for i in range(idx_obj3)]
        results.append(arr)

for result in results:
    print(result)

希望这能有所帮助!

相关问题