【问题标题】:how to fill up a table row by row in python? I tried append but it didn't work如何在python中逐行填写表格?我尝试了追加,但没有奏效
【发布时间】:2022-01-04 10:03:22
【问题描述】:

我想找到数字 {0,1,2,3,4} 的所有组合,并将它们打印在表格中,第一列是订单号,第二列是特定组合。我想要的输出应采用以下形式:

1 (0,)

2 (1,)

... ...

6 (0,1)

... ...

我尝试了以下代码

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)

但生成的表格是一条水平线,而不是具有两列的二维矩形表格。我该如何解决这个问题?谢谢!

【问题讨论】:

  • 你的意思是像stackoverflow.com/q/35684318/17635987 吗?
  • @kirjosieppo 谢谢!我刚刚在问题中添加了我想要的输出。您认为这可以使用您提供的链接完成吗?

标签: python arrays numpy append


【解决方案1】:

这是一个非常简单的解决方案:

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 自动生成行号。

【讨论】:

  • 非常感谢!这很有帮助,完全解决了我的问题。实际上,不需要通过逐行填充将数据存储在 2D 表中。一次打印两个对象就足够了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-07-27
  • 2017-11-26
  • 2019-07-10
  • 2021-03-22
  • 2016-10-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多