Thursday, May 12, 2022

[FIXED] how to fill up a table row by row in python? I tried append but it didn't work

Issue

I want to find all combinations of numbers {0,1,2,3,4}, and print them out in a table, with the first column being the order number and the second column being a particular combination. My desired output should take the following form:

1 (0,)

2 (1,)

... ...

6 (0,1)

... ...

I tried the following codes

import numpy as np
import itertools
rows=list(range(5))
combrows=[]
for k in range(1,5):  #the number of rows k takes values from 1 to 5
    for combo in itertools.combinations(rows,k):
        combrows.append(combo)

ind=1
store=[]
for i in combrows:
    store.append([[ind],[i]])
    ind=ind+1
print(store)

But the resulting table is a horizontal line instead of a 2D rectangular table with two columns. How could I fix this? Thanks!


Solution

This is a quite straightforward solution:

from itertools import combinations
numbers = list(range(5))
lst = []
for l in (combinations(numbers, r) for r in range(1, 5)):
    lst.extend(l)
for i, j in enumerate(lst):
    print(i+1, j)

Try it online!

enumerate generates the line numbers automatically.



Answered By - kirjosieppo
Answer Checked By - Robin (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.