您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python分割功能。太多值无法解包错误

Python分割功能。太多值无法解包错误

您试图将拆分列表解包为这两个变量。

url, count = line.split()

如果没有空间或两个或多个空间怎么办?其余的单词会去哪儿?

data = "abcd"
print data.split()    # ['abcd']
data = "ab cd"
print data.split()    # ['ab', 'cd']
data = "a b c d"
print data.split()    # ['a', 'b', 'c', 'd']

您实际上可以在分配前检查长度

with open(urls_file_path, "r") as f:
    for idx, line in enumerate(f, 1):
        split_list = line.split()
        if len(split_list) != 2:
            raise ValueError("Line {}: '{}' has {} spaces, expected 1"
                .format(idx, line.rstrip(), len(split_list) - 1))
        else:
            url, count = split_list
            print url, count

使用输入文件

http://google.com 2
http://python.org 3
http://python.org 4 Welcome
http://python.org 5

这个程序会产生

$ python Test.py
Read Data: http://google.com 2
Read Data: http://python.org 3
Traceback (most recent call last):
  File "Test.py", line 6, in <module>
    .format(idx, line.rstrip(), len(split_list) - 1))
ValueError: Line 3: 'http://python.org 4 Welcome' has 2 spaces, expected 1

在@abarnert的评论之后,您可以使用partition像这样的函数

url, _, count = data.partition(" ")

如果有多个空格/没有空格,count则将分别保留其余字符串或空字符串。

可以执行以下操作

first, second, *rest = data.split()

在Python 3.x中,前两个值将分别在first和中分配,second列表的其余部分将分配给rest

python 2022/1/1 18:33:00 有453人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶