Add a list to combinations

Viewed 54

I have list, A, containing 8 values. I like to make combinations first, then add two more points in list B to each combination. Here is my code:

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)

But I got an error:

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

Expected results:

[[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]]
2 Answers

Type tuple (return by combinations) is immutable, you may use a list and populate it with the item and B

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

Or return list of list from your combination

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

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

You can use also map function, to get list of list.

map() function returns a map object(which is an iterator) of the results after applying the given function to each item of a given iterable (in your case list)

instead of:

com = combination(A, n)

use:

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