我有一本像这样的字典:
a = {'date' : ['2012-03-09', '2012-01-12', '2012-11-11'],
'rate' : ['199', '900', '899'],
'country code' : ['1', '2', '44'],
'area code' : ['114', '11', '19'],
'product' : ['Mobile', 'Teddy', 'Handbag']}
然后我使用 zip 函数连接这些值:
data = [(a,b,c+d,e) for a,b,c,d,e in zip(*a.values())]
输出:
data = [('2012-03-09', '199', '1114', 'Mobile'),
('2012-01-12', '900', '211', 'Teddy'),
('2012-11-11', '899', '4419', 'Handbag')]
如果我想让函数自己搜索“国家代码”和“区号”,然后合并它们,该怎么办?有什么建议吗?
最佳答案
合并“列”的通用方法,让您指定预期的列以及预先合并的内容:
def merged_pivot(data, *output_names, **merged_columns):
input_names = []
column_map = {}
for col in output_names:
start = len(input_names)
input_names.extend(merged_columns.get(col, [col]))
column_map[col] = slice(start, len(input_names))
for row in zip(*(data[c] for c in input_names)):
yield tuple(''.join(row[column_map[c]]) for c in output_names)
你调用的是:
list(merged_pivot(a, 'date', 'rate', 'code', 'product', code=('country code', 'area code')))
传入:
- 映射列表
- 构成输出的每一列(上例中的
'date', 'rate', 'code', 'product'
) - 输出中由输入列的合并列表组成的任何列(示例中为
code=('country code', 'area code')
,因此输出中的code
是通过合并country code
和area code
形成的)。
输出:
>>> list(merged_pivot(a, 'date', 'rate', 'code', 'product', code=('country code', 'area code')))
[('2012-03-09', '199', '1114', 'Mobile'), ('2012-01-12', '900', '211', 'Teddy'), ('2012-11-11', '899', '4419', 'Handbag')]
或者,稍微重新格式化:
[('2012-03-09', '199', '1114', 'Mobile'),
('2012-01-12', '900', '211', 'Teddy'),
('2012-11-11', '899', '4419', 'Handbag')]
而不是调用 list()
在 merged_pivot()
上生成器,如果您需要做的只是分别处理每一行,您也可以循环遍历它的输出:
columns = ('date', 'rate', 'code', 'product')
for row in merged_pivot(a, *columns, code=('country code', 'area code')):
# do something with `row`
print row
关于python - 连接同一字典中两个键的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15293142/