Python - ValueError: too many values to unpack - why?

Python - ValueError: too many values to unpack - why?

我对 Python 很陌生。我需要比较两个单词列表并检测一个列表中不在另一个列表中的那些单词。 这里有两个测试文件

big_list.txt

[coin, co-operate, accurate, achieve, adapt, adjust, admire, admission, enter, advance, adventure, aeroplane, plane, affair, aim, objective, annual, approach, approve, argument]

small_list.txt

[coin, co-operate,  football, accurate, achieve, adapt, amazing, adjust, admire, admission, enter, advance, breakfast]

具有此预期输出

[football, amazing, breakfast] 

我这里有一个非常简单的 Python 脚本

from sys import argv
big_list, small_list = argv
blist = open(big_list).read()
slist = open(small_list).read()
dlist = [item for item in slist if item not in blist]
diff_list = open(dlist, 'w').write()
diff_list.close()

但是当运行它returns这个错误信息

roy@medea:~/e2tw/list_comparison$ python file_comp1.py big_list.txt small_list.txt
  Traceback (most recent call last):
       File "file_comp1.py", line 3, in <module>
          big_list, small_list = argv
   ValueError: too many values to unpack

尝试:

big_list, small_list = argv[1:]

为什么?因为默认会给你的脚本传递三个个参数,其中argv[0]是脚本名

P.S。在你的最后两行中,有一个 bug 等待关闭。您不能 将列表作为对文件对象的引用进行传递。你应该这样做:

output_file = open("filename.txt", "w")
output_file.write("[%s]" % ", ".join(dlist))
output_file.close()

至少尝试(请查看第二个代码片段以获得真正有效的答案):

from sys import argv
big_list, small_list = argv[-2:]
blist = open(big_list).read()
slist = open(small_list).read()
dlist = [item for item in slist if item not in blist]
diff_list = open(dlist, 'w').write()
diff_list.close()

第一个条目将始终是您的脚本本身,但正如其他人已经部分指出的那样,有许多内容无法正常工作。查看下面的工作代码 :-) 让你继续。

您还可以使用更广泛使用的 [1:] 来忽略索引 0 处的第一个条目并获取所有其余条目。在 hackish/rookie 代码中,我更喜欢显式的 -"number of expected" 参数。

但也许最好写 这样的东西 开始:

#! /usr/bin/env python
from __future__ import print_function
import sys


def read_list_from_file(a_path):
    """Simple parser transforming a [a, b,] text in file
    at a_path into a list."""
    return [z.strip() for z in open(a_path, 'rt').read().strip('[]').split(',')]


def a_not_in_b_list(a_seq, b_seq):
    """Return the list of entries in a_seq but not in b_seq."""
    return [item for item in a_seq if item not in b_seq]


def main():
    """Drive the diff."""
    if len(sys.argv) == 3:
        big_list, small_list = sys.argv[1:]
    else:
        print("Usage:", __file__, "<big-list-file> <small-list-file>")
        return 2
    # Do something with the file names given here
    b_list = read_list_from_file(big_list)
    s_list = read_list_from_file(small_list)

    with open('diff_list.txt', 'w') as f:
        f.write('%s\n' % (repr(a_not_in_b_list(s_list, b_list)),))


if __name__ == '__main__':
    sys.exit(main())

运行 你的文本文件中的这个 diff_list.txt:

['football', 'amazing', 'breakfast']

argv[0] 包含 python 脚本的名称 运行 (类似于 C 的 argv[0] 具有可执行名称的方式)。您显然不能将三个值 (['file_comp1.py', 'big_list.txt', 'small_list.txt']) 分配给两个变量。例如,您可以切片 argv 以仅获取第二个参数及以后的参数:

big_list, small_list = argv[1:]
from sys import argv
big_list = argv[1]
small_list = argv[2]
blist = open(big_list).read()
slist = open(small_list).read()
dlist = [item for item in slist if item not in blist]
diff_list = open(dlist, 'w').write()
diff_list.close()

查看这个关于如何使用 argv 的答案。Using argv

argv[0]是脚本名称。