【问题标题】:Python dictionary generation, too many variables to unpackPython字典生成,太多变量解包
【发布时间】:2014-02-06 19:52:21
【问题描述】:

尝试从从 .csv 文件解析的数据列表生成字典。收到错误“太多的值无法解包”,有任何关于修复的想法吗?

将有重复的键/多个值附加到每个键。

我对 python 和编程很陌生,所以如果你能添加一个关于哪里出了问题/如何修复的简短解释,请。

脚本下方是打印 res 时显示的数据。

#!/usr/bin/python
import csv
import pprint
pp = pprint.PrettyPrinter(indent=4)
import sys
import getopt
res = []

import argparse
parser = argparse.ArgumentParser()

parser.add_argument ("infile", metavar="CSV", nargs="+", type=str, help="data file") 
args = parser.parse_args()

with open("out.csv","wb") as f:
    output = csv.writer(f) 
    for filename in args.infile:
        for line in csv.reader(open(filename)): 
            for item in line[2:]:

                #to skip empty cells
                if not item.strip():
                    continue

                item = item.split(":")
                item[1] = item[1].rstrip("%")

#               print([line[1]+item[0],item[1]])
                res.append([line[1]+item[0],item[1]])
#               output.writerow([line[1]+item[0],item[1].rstrip("%")])

pp.pprint( res )

from collections import defaultdict
initial_list = [res]

d = defaultdict(list)
pp.pprint( d )  
for k, v in initial_list:
    d[k].append(float(v))  # possibly `int(v)` ?

和控制台

[   ['P1L', '2.04'],
    ['Q2R', '1.93'],
    ['V3I', '20.03'],
    ['V3M', '78.18'],
    ['V3S', '1.67'],
    ['T4L', '1.16'],
    ['T12N', '75.60'],
    ['T12S', '22.73'],
    ['K14E', '1.03'],
    ['K14R', '50.65'],
    ['I15*', '63.94'],
    ['I15V', '35.30'],
    ['G17A', '38.31'],
    ['Q18R', '38.43'],
    ['L19T', '98.62'],
    ['L24*', '2.18'],
    ['D25E', '1.87'],
    ['D25N', '2.17'],
    ['M36I', '99.76'],
    ['S37N', '97.23'],
    ['R41K', '99.03'],
    ['L63V', '99.42'],
    ['H69K', '99.30'],
    ['I72V', '5.76'],
    ['V82I', '98.70'],
    ['L89M', '98.49'],
    ['I93L', '99.64'],
    ['P4S', '99.09'],
    ['V35T', '99.26'],
    ['E36A', '98.23'],
    ['T39D', '98.78'],
    ['G45R', '3.11'],
    ['S48T', '99.70'],
    ['V60I', '99.44'],
    ['K102R', '1.04'],
    ['K103N', '99.11'],
    ['G112E', '2.77'],
    ['D123N', '8.14'],
    ['D123S', '91.12'],
    ['I132M', '1.41'],
    ['K173A', '99.55'],
    ['Q174K', '99.68'],
    ['D177E', '98.95'],
    ['G190R', '2.56'],
    ['E194K', '2.54'],
    ['T200A', '99.28'],
    ['Q207E', '98.75'],
    ['R211K', '98.77'],
    ['W212*', '3.00'],
    ['L214F', '99.25'],
    ['V245E', '99.30'],
    ['E248D', '99.58'],
    ['D250E', '99.02'],
    ['T286A', '99.70'],
    ['K287R', '1.78'],
    ['E291D', '99.22'],
    ['V292I', '98.28'],
    ['I293V', '99.58'],
    ['V317A', '28.20'],
    ['L325V', '2.40'],
    ['G335D', '98.33'],
    ['F346S', '4.42'],
    ['N348I', '3.81'],
    ['R356K', '71.43'],
    ['M357I', '20.00'],
    ['M357T', '80.00']]
defaultdict(<type 'list'>, {})
Traceback (most recent call last):
  File "test.py", line 40, in <module
    for k, v in initial_list:
ValueError: too many values to unpack

【问题讨论】:

    标签: python python-2.7


    【解决方案1】:

    您将结果包装在一个列表中:

    initial_list = [res]
    

    然后尝试遍历列表:

    d = defaultdict(list)
    pp.pprint( d )  
    for k, v in initial_list:
        d[k].append(float(v))  # possibly `int(v)` ?
    

    您想改为循环遍历 res

    d = defaultdict(list)
    for k, v in res:
        d[k].append(float(v))
    

    您可以在 CSV 读取循环中完成所有这些操作

    from collections import defaultdict
    d = defaultdict(list)
    
    with open("out.csv","wb") as f:
        output = csv.writer(f) 
        for filename in args.infile:
            for line in csv.reader(open(filename)): 
                for item in line[2:]:
    
                    #to skip empty cells
                    if not item.strip():
                        continue
    
                    key, value = item.split(":", 1)
                    value = value.rstrip("%")
    
                    d[line1[1] + key].append(float(value))
    

    【讨论】:

    • 谢谢你,再次感谢您的解释,因为我才刚开始学习几周,这确实有帮助。
    猜你喜欢
    • 1970-01-01
    • 2018-09-30
    • 2017-12-05
    • 2020-01-18
    • 2016-06-23
    • 2019-01-17
    • 2017-03-02
    • 2022-11-13
    • 2018-03-21
    相关资源
    最近更新 更多