Ask Your Question
0

How can the output of combinations in Python be separated?

asked 2023-03-21 11:00:00 +0000

scrum gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2022-03-15 16:00:00 +0000

woof gravatar image

We can separate the output of combinations in Python in a few different ways:

  1. Convert the output to a list of tuples: We can use the list() function to convert the output of combinations to a list of tuples, which can then be accessed individually using indexes.
from itertools import combinations

sample_list = [1, 2, 3, 4]
comb_list = list(combinations(sample_list, 2))

# Output: [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
  1. Use a for loop to iterate through the output: We can use a for loop to iterate through the output of combinations and print each combination on a new line.
from itertools import combinations

sample_list = [1, 2, 3, 4]
comb_list = combinations(sample_list, 2)

for i in comb_list:
    print(i)

# Output:
# (1, 2)
# (1, 3)
# (1, 4)
# (2, 3)
# (2, 4)
# (3, 4)
  1. Use join() function to join the output as a string: We can join the output of combinations as a string using the join() function and specify a separator.
from itertools import combinations

sample_list = [1, 2, 3, 4]
comb_list = combinations(sample_list, 2)
comb_str = '\n'.join([' '.join(map(str, tpl)) for tpl in comb_list])

print(comb_str)

# Output:
# 1 2
# 1 3
# 1 4
# 2 3
# 2 4
# 3 4
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-03-21 11:00:00 +0000

Seen: 7 times

Last updated: Mar 15 '22