python - 有多个值需要解压

标签 python string dictionary arguments iterable-unpacking

我运行这段代码:

def score(string, dic):
    for string in dic:
        word,score,std = string.lower().split()
        dic[word]=float(score),float(std)
        v = sum(dic[word] for word in string)
        return float(v)/len(string)

并得到这个错误:

word,score,std = string.split()
ValueError: need more than 1 value to unpack

最佳答案

这是因为 string.lower().split() 返回的列表只有一个项目。你不能将它分配给 word,score,std 除非这个列表恰好有 3 个成员;即 string 恰好包含 2 个空格。


a, b, c = "a b c".split()  # works, 3-item list
a, b, c = "a b".split()  # doesn't work, 2-item list
a, b, c = "a b c d".split()  # doesn't work, 4-item list

关于python - 有多个值需要解压,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12990551/

相关文章:

Python:检查是否有任何列表元素是字典中的键

python - 我们如何解压一个任意嵌套的迭代器、迭代器、[...]、迭代器?

python - 在 Python 中收集 webViewLink 和 webContentLink

python - Djangobulk_Create,大型csv文件

java - 在 Java 中将 XML 文档复制到字符串变量中

c# - 字符串输出 : format or concat in C#?

python - 使用 format() 舍入、对齐和打印浮点列表

java - StringIndexOutOfBoundsException,从字符串方法中删除空格

python - 修改Python字典中的列表元素

ios - 在字典键值对中,如何将值(其中value可以是不同类型的类型)解包为String