-2

I'm trying to access the elements of a list of combinations as arrays, to be able to manipulate the results of the combinations.

a = 1
b = 2
c = 3
d = 4
comb = combinations_with_replacement([a, b, c, d], 2)

for i in list(comb): 
    print(i) 

I have this code, the a, b, c, d variables aren't going to be those specific values. This returns:

(1, 1)
(1, 2)
(1, 3)
(1, 4)
(2, 2)
(2, 3)
(2, 4)
(3, 3)
(3, 4)
(4, 4)

I want to be able to access each of those combinations as a array to manipulate its elements, how do I do that?

Nillmer
  • 159
  • 1
  • 7

2 Answers2

1

Write a wrapper.

def wrapper_combinations_with_replacement(iterable, r):
    comb = combinations_with_replacement(iterable, r)
    for item in comb:
        yield list(item)

Now you have a list of lists.

a = 1
b = 2
c = 3
d = 4
comb = wrapper_combinations_with_replacement([a, b, c, d], 2)
for i in list(comb): 
    print(i)

The result is:

[1, 1]
[1, 2]
[1, 3]
[1, 4]
[2, 2]
[2, 3]
[2, 4]
[3, 3]
[3, 4]
[4, 4]

Or use list

list(wrapper_combinations_with_replacement([a, b, c, d], 2))

And the result:

[[1, 1],
 [1, 2],
 [1, 3],
 [1, 4],
 [2, 2],
 [2, 3],
 [2, 4],
 [3, 3],
 [3, 4],
 [4, 4]]
ErdoganOnal
  • 800
  • 6
  • 13
0
comb_list = [list(combination) for combination in (list(comb))]

This will give you a list of combinations as arrays

for array_combination in comb_list:
    print(array_combination)

Output:

> [1, 1]
  [1, 2]
  [1, 3]
  [1, 4]
  [2, 2]
  [2, 3]
  [2, 4]
  [3, 3]
  [3, 4]
  [4, 4]
Harshit
  • 1,510
  • 19
  • 42
Ed Hawk
  • 41
  • 1
  • 3