将列表添加到组合中

2024-06-09 01:32:06 发布

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

我有一个列表A,包含8个值。我喜欢先进行组合,然后在列表B中为每个组合再添加两个点。这是我的密码:

def combination(arr, r):
    return list(itertools.combinations(arr, r))
A = [[0.0, 0.0, 0.0], [0.0, 0.5, 0.0], [0.5, 0.0, 0.5], [0.5, 0.5, 0.5], [0.0, 0.25, 0.0], [0.0, 0.7499999819999985, 0.0], [0.5, 0.25, 0.5], [0.5, 0.7499999819999985, 0.5]]
B = [[0.4950293947410103, 0.5021785267638279, 0.4935703740156043], [1, 1, 1]]
n = 1 #can be change
com = combination(A, n)
for item in com:
    item.extend(B)
    print(item)

但我有一个错误:

AttributeError: 'tuple' object has no attribute 'extend'

预期成果:

[[0.0, 0.0, 0.0], [0.4950293947410103, 0.5021785267638279, 0.4935703740156043], [1, 1, 1]]
[[0.0, 0.5, 0.0], [0.4950293947410103, 0.5021785267638279, 0.4935703740156043], [1, 1, 1]]
[[0.5, 0.0, 0.5], [0.4950293947410103, 0.5021785267638279, 0.4935703740156043], [1, 1, 1]]
[[0.5, 0.5, 0.5], [0.4950293947410103, 0.5021785267638279, 0.4935703740156043], [1, 1, 1]]
[[0.0, 0.25, 0.0], [0.4950293947410103, 0.5021785267638279, 0.4935703740156043], [1, 1, 1]]
[[0.0, 0.7499999819999985, 0.0], [0.4950293947410103, 0.5021785267638279, 0.4935703740156043], [1, 1, 1]]
[[0.5, 0.25, 0.5], [0.4950293947410103, 0.5021785267638279, 0.4935703740156043], [1, 1, 1]]
[[0.5, 0.7499999819999985, 0.5], [0.4950293947410103, 0.5021785267638279, 0.4935703740156043], [1, 1, 1]]

Tags: com密码列表returndefbeitemcan
2条回答

您还可以使用映射函数,以获取列表的列表

map()函数将给定函数应用于给定iterable(在案例列表中)的每个项后,返回结果的映射对象(迭代器)

而不是:

com = combination(A, n)

使用:

com = map(list, combination(A, n))

类型tuple(通过组合返回)是不可变的,您可以使用list并用itemB填充它

com = combination(A, n)
com = [[*item, *B] for item in com]

或者从组合中返回列表的列表

def combination(arr, r):
    return [list(c) for c in itertools.combinations(arr, r)]

# ...
for item in com:
    item.extend(B)

相关问题 更多 >