我有两个数组。 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
谢谢!
答案 0 :(得分: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
答案 1 :(得分:1)
使用pandas和numpy很容易,结果将是一个更有用的表。熊猫擅长安排表格数据。因此,让我们利用它: 用以下命令安装熊猫:
pip install pandas
#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
num = numpy.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 :(得分: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]
答案 3 :(得分:0)
您需要执行两个子步骤。
首先,您希望将列表分成多个块,然后再将这些块分配给字典。
要将列表分成多个部分,我们可以创建一个函数:
Functor
这时我们将有: [[1,4,7],[2,5,8],[3,6,9]]
从这里开始,创建dict非常简单。首先,我们将两个列表压缩在一起:
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
利用Python知道如何将元组列表转换为字典这一事实:
zip(column_names, chunk(3))
答案 4 :(得分: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))))