Python-ValueError:要解包的值太多-为什么?

Python-ValueError:要解包的值太多-为什么?,python,argv,Python,Argv,我对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]

我对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()
但当运行时,它会返回此错误消息

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
roy@medea:~/e2tw/list\u比较$python文件\u comp1.py big\u list.txt small\u list.txt
回溯(最近一次呼叫最后一次):
文件“File_comp1.py”,第3行,在
大列表,小列表=argv
ValueError:要解压缩的值太多
试试:

为什么??因为默认情况下,三个参数将传递给脚本,脚本名称为
argv[0]

另外,在你的最后两行中,有一个bug正等着你去处理。不能将列表作为对文件对象的引用传递。您应该这样做:

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

为什么??因为默认情况下,三个参数将传递给脚本,脚本名称为
argv[0]

另外,在你的最后两行中,有一个bug正等着你去处理。不能将列表作为对文件对象的引用传递。您应该这样做:

output_file = open("filename.txt", "w")
output_file.write("[%s]" % ", ".join(dlist))
output_file.close()
请至少尝试一下(请查看第二个代码片段,以获得真正完全有效的答案)

第一个条目始终是您的脚本本身,但是有许多事情没有像其他人已经部分指出的那样起作用。查看下面的工作代码:-)以使您继续

您还可以使用
[1:://code>,它更广泛地用于忽略索引0处的第一个条目,并获取所有剩余条目。但在hackish/rookie代码中,我更喜欢显式的“预期数量”参数

但也许最好写一些类似这样的东西来开始:

#! /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())
请至少尝试一下(请查看第二个代码片段,以获得真正完全有效的答案)

第一个条目始终是您的脚本本身,但是有许多事情没有像其他人已经部分指出的那样起作用。查看下面的工作代码:-)以使您继续

您还可以使用
[1:://code>,它更广泛地用于忽略索引0处的第一个条目,并获取所有剩余条目。但在hackish/rookie代码中,我更喜欢显式的“预期数量”参数

但也许最好写一些类似这样的东西来开始:

#! /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())

argv[0]
包含正在运行的python脚本的名称(类似于C的
argv[0]
具有可执行文件名称的方式)。显然,您不能将三个值(
['file\u comp1.py'、'big\u list.txt'、'small\u list.txt']
)关联为两个变量。例如,您可以使用slice
argv
仅获取第二个参数及其后续参数:


argv[0]
包含正在运行的python脚本的名称(类似于C的
argv[0]
具有可执行文件名称的方式)。显然,您不能将三个值(
['file\u comp1.py'、'big\u list.txt'、'small\u list.txt']
)关联为两个变量。例如,您可以使用slice
argv
仅获取第二个参数及其后续参数:

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

argv[0]
是脚本名称

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


argv[0]
是脚本名。

确切地说:sys.argv也包含脚本名–@starfury感谢linkdlist在其代码中提供输出['z','k'],为什么?确切地说:sys.argv也包含脚本名–@starfury感谢linkdlist提供输出['z','k']在他的代码中为什么?旁注:最后几行是怎么回事?您正在打开一个
列表
写入
-ing不向其添加任何内容,存储从
写入
返回的内容(提示:不是文件对象),然后
关闭
-ing非文件。另外,
read
ing包含Python
list
文本的文件不会创建
list
s。您需要
ast.literal\u eval
将Python文本形式的字符串转换为实际的Python对象,而不是原始字节。由于您对Python非常陌生,我认为我们不应该否决您的问题。看看我建议的答案,我认为这段代码应该有足够的样板文件来帮助您编写可靠的代码并进一步试验您的任务。如果有错误,请评论,我会改正。谢谢。@ShadowRanger你的观察非常有效。需要注意的是,OP的文件内容不能用
ast
直接计算,因为列表中的项目不是字符串文字。@MosesKoledoye:取决于问题描述的格式是否准确。所需的最终结果也不能用Python表示(除了糟糕的手动格式化之外),因此它可能是“伪数据”?您正在打开一个
列表
写入
-ing不向其添加任何内容,存储从
写入
返回的内容(提示:不是文件对象),然后
关闭
-ing非文件。另外,
read
ing包含Python
list
文本的文件不会创建
list
s。您需要
ast.literal\u eval
将Python文本形式的字符串转换为实际的Python对象,而不是原始字节。由于您对Python非常陌生,我认为我们不应该否决您的问题。看看我建议的答案,我认为这段代码应该有足够的样板文件来帮助您编写可靠的代码并进一步试验您的任务。如果有错误,请评论,我会改正。谢谢。@ShadowRanger你的观察非常有效。需要注意的是,OP的文件内容不能用
ast
直接计算,因为列表中的项目不是字符串文字。@MosesKoledoye:取决于问题描述的格式是否准确。所需的最终结果也不能用Python表示(除了糟糕的手动格式化之外),因此它可能是“伪数据”。@Dilettante感谢您
['football', 'amazing', 'breakfast']
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()