将列表转换为表格 - Python

3
我是一名可以翻译文本的助手。
我有两个数组:column_names保存列标题,values保存所有值。
我了解如果这样做:
column_names = ["a", "b", "c"]
values = [1, 2, 3]
for n, v in zip(column_names, values):
    print("{} = {}".format(n, v))

I get

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

谢谢你!
5个回答

5

使用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

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

另外,您还可以使用itertools中定义的grouper

>>> 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

1

itertools.cycle 在这种情况下似乎很合适。以下是另一种版本,供未来读者参考:

import itertools

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

L = zip(itertools.cycle(column_names), values)

for g, v in itertools.groupby(sorted(L), lambda x: x[0]):
    print("{} = {}".format(g, [i[1] for i in v]))

给出:
a = [1, 4, 7]
b = [2, 5, 8]
c = [3, 6, 9]

0

这个任务有两个子步骤需要完成。

首先,您需要将列表分成块,然后将这些块分配给一个字典。

为了将列表分成块,我们可以创建一个函数:

def chunk(values, chunk_size):
    assert len(values)%chunk_size == 0 # Our chunk size has to evenly fit in our list
    steps = len(values)/chunk_size
    chunky_list = []
    for i in range(0,steps):
        position = 0 + i
        sub_list = []
        while position < len(values):
            sub_list.append(values[position])
            position += chunk_size
        chunky_list.append(sub_list)
    return chunky_list

此时我们将会有: [[1,4,7],[2,5,8],[3,6,9]]

从这里开始,创建字典非常容易。首先,我们将这两个列表压缩在一起:

zip(column_names, chunk(3))

利用Python知道如何将元组列表转换为字典的优势:
dict(zip(column_names, chunk(3)))

0

你也可以使用切片和 collections.defaultdict 来收集你的值:

from collections import defaultdict

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

column_len = len(column_names)

d = defaultdict(list)
for i in range(0, len(values), column_len):
    seq = values[i:i+column_len]

    for idx, number in enumerate(seq):
        d[column_names[idx]].append(number)

for k, v in d.items():
    print('%s = %s' % (k, ', '.join(map(str, v))))

输出结果为:

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

如果使用itertools.cycle创建压缩列表,可以避免切片,从而改进此问题:

from collections import defaultdict
from itertools import cycle

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

column_names = cycle(column_names)

d = defaultdict(list)
for column, val in zip(column_names, values):
    d[column].append(val)

for k, v in d.items():
    print('%s = %s' % (k, ', '.join(map(str, v))))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接