2

我寻找一种将变量保存到文件中的方法(使它们持久用于其他计算)。

我找到了一些解决方案,例如:https ://stackoverflow.com/a/899199/1846113 但是当我在如下列表中实现它时:

import pickle

list = [['cccc',['asd','sdad','sdadas']],['cscc',['asd','sdad','sdadas']]]
pickle.dump(list, outfile)

它给了我这个错误

 File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1370, in dump
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 224, in dump
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 286, in save
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 600, in save_list
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 615, in _batch_appends
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 286, in save
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 600, in save_list
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 615, in _batch_appends
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 286, in save
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 739, in save_global
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 811, in whichmodule
TypeError: unhashable type: 'list'

有谁知道问题是什么?还是其他解决方案?


编辑:有解决方案

问题是我在创建列表时出错。我会发布它(这样你就可以笑了)并避免这个愚蠢的错误:我通过使用(丑陋的)函数处理列表的一些元素来创建列表:

def process_element(doc):
    processed_value = do_something(doc.pop())
    return [doc.pop, processed_value] 

正如你们中的一些人已经注意到的那样,我在返回输出时出错:

[doc.pop, processed_value]

我在列表中添加了一个不可散列的方法,给了我错误。正确的版本是:

def process_element(doc):
    processed_value = do_something(doc.pop())
    return [doc.pop(), processed_value] 

谢谢。

4

2 回答 2

0

一个更简单的方法是使用with,像这样forenumerate

with open('input.txt', 'r') as f, open('output.txt', 'w') as o:
    for numline, line in enumerate((line.split() for line in f), start=1):
        # process line elements by using line[0] line[1]...

    # When you're done, you can write results in an output file like this
    # (add a loop if needed):
    o.write("%s %s\n" % (results[0], results[1]))

等等瞧!

于 2014-09-22T12:55:58.573 回答
0

对于您的示例列表和大多数其他示例,我将使用 JSON 文件格式:

导入json

lst = [['cccc',['asd','sdad','sdadas']],['cscc',['asd','sdad','sdadas']]]
with open('list.json', w) as jsonout:
    json.dump(lst, jsonout)

# and then
with (open('list.json') as jsonin:
    lst = json.load(jsonin)
于 2014-09-22T13:07:43.907 回答