将列表转换为表 \- python

新手上路,请多包涵

我有两个数组。 column_names 保留列标题。 values 保存所有值。

我明白如果我这样做:

 column_names = ["a", "b", "c"]
values = [1, 2, 3]
for n, v in zip(column_names, values):
    print("{} = {}".format(n, v))

我得到

a = 1
b = 2
c = 3

如果我通过了,我该如何编码:

 column_names = ["a", "b", "c"]
values = [1, 2, 3, 4, 5, 6, 7, 8, 9]

我会得到

a = 1, 4, 7
b = 2, 5, 8
c = 3, 6, 9

谢谢!

原文由 RJK 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 427
2 个回答

您可以按如下方式进行

>>> for n, v in zip(column_names, zip(*[values[i:i+3] for i in range(0,len(values),3)])):
...     print("{} = {}".format(n, ', '.join(map(str, v))))
...
a = 1, 4, 7
b = 2, 5, 8
c = 3, 6, 9

或者,您可以使用 grouper 中定义的 itertools

 >>> def grouper(iterable, n, fillvalue=None):
...     "Collect data into fixed-length chunks or blocks"
...     # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
...     args = [iter(iterable)] * n
...     return zip_longest(*args, fillvalue=fillvalue)
...
>>> from itertools import zip_longest
>>> for n, v in zip(column_names, zip(*grouper(values, 3))):
...     print("{} = {}".format(n, ', '.join(map(str, v))))
...
a = 1, 4, 7
b = 2, 5, 8
c = 3, 6, 9

原文由 Sunitha 发布,翻译遵循 CC BY-SA 4.0 许可协议

使用 pandas 和 numpy 这很容易,结果将是一个更有用的表格。 Pandas 擅长排列表格数据。因此,让我们利用它:使用以下命令安装 pandas:

 pip install pandas --user

 #pandas comes with numpy
import numpy as np
import pandas as pd

# this makes a normal python list for integers 1-9
input = list(range(1,10))

#lets convert that to numpy array as np.array
num = np.array(input)

#currently its shape is single dimensional, lets change that to a two dimensional matrix that turns it into the clean breaks you want
reshaped = num.reshape(3,3)

#now construct a beautiful table
pd.DataFrame(reshaped, columns=['a','b','c'])

#ouput is
   a  b  c
0  1  2  3
1  4  5  6
2  7  8  9

原文由 csevier 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题