【问题标题】:Problem trying to read back zip list into original lists尝试将 zip 列表读回原始列表时出现问题
【发布时间】:2021-03-12 19:01:24
【问题描述】:

三个月刚开始学习 Python,感谢大家的帮助。令人惊叹的语言。

在尝试回读保存到 csv 的 zip 列表时遇到问题。

这是我将列表写入文件的方式..

def save_csv():
    buyall = list(zip(buycoin, buyprice, buyqty, buystatus))  
    with open('Trade Data.csv', 'wt') as myfile:
        wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
        wr.writerow(buyall)

从文件加载时,如何将这 4 个列表读回列表本身? 无法确定格式..

问候, 杰夫

【问题讨论】:

    标签: python list csv zip


    【解决方案1】:

    请阅读代码中的注释

    import csv
    
    buycoin, buyprice, buyqty, buystatus = [
        (str(i), str(i)*(i+1), str(i)+'*') for i in range(4)]
    print(buycoin, buyprice, buyqty, buystatus)
    # ('0', '0', '0*') ('1', '11', '1*') ('2', '222', '2*') ('3', '3333', '3*')
    
    
    def save_csv():
        buyall = list(zip(buycoin, buyprice, buyqty, buystatus))
        print(*buyall)
        # ('0', '1', '2', '3') ('0', '11', '222', '3333') ('0*', '1*', '2*', '3*')
        with open('Trade Data.csv', 'wt') as myfile:
            wr = csv.writer(myfile)  # remove quoting
            wr.writerows(buyall)  # row's'
    
    
    def read_csv():
        with open('Trade Data.csv', 'rt') as myfile:
            data = csv.reader(myfile)
            data = [*zip(*data)]  # transpose
            return data
    
    
    save_csv()
    '''
    0,1,2,3
    0,11,222,3333
    0*,1*,2*,3*
    '''
    
    a, b, c, d = read_csv()
    print(a, b, c, d)
    # ('0', '0', '0*') ('1', '11', '1*') ('2', '222', '2*') ('3', '3333', '3*')
    

    【讨论】:

    • 感谢迈克尔的回复。不幸的是,有些事情不太正确..收到此错误.. c:\Temp\Project4>python rtest.py ('0', '0', '0*') ('1', '11', '1* ') ('2', '222', '2*') ('3', '3333', '3*') ('0', '1', '2', '3') ('0' ', '11', '222', '3333') ('0*', '1*', '2*', '3*') Traceback (最近一次调用最后): 文件 "rtest.py",第 27 行,在 a, b, c, d = read_csv() ValueError: not enough values to unpack (expected 4, got 0)
    • 想通了...我不应该使用 list(zip( 来捆绑,应该只是 zip.. list 添加了额外的 [ ] 导致它看起来像 1(或 0?)而不是 4.. :) 谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多