请问有人对此提出一些意见。
for line in oscars_file:
if '-' in line:
years,oscars=line.strip().split('-')
我在终端收到此错误:
ValueError: too many values to unpack (expected 2)
oscars文件的一个例子是:
1975 - "One Flew over the Cuckoo's Nest"
1973 - "The Sting"
答案 0 :(得分:4)
您的部分文字可能包含多个'-'
。为此,你应该这样做:
for line in oscars_file:
if '-' in line:
years,oscars=line.strip().split('-',1)
split('-',1)
只进行一次分割,这是您想要的第一次分割。
>>> s = '1-2-3-4'
>>> print s.split('-',1)
['1','2-3-4']
>>> print s.split('-',2)
['1','2','3-4']