简体   繁体   English

我的Python代码有什么问题? Head First Python中的示例

[英]What's wrong with my Python code? Example in Head First Python

It says 它说

 james.append(sanitize(each_item))  
 (mins, secs) = time_string.split(splitter)

 need more than 1 value to unpack

What's wrong? 怎么了? Thank you. 谢谢。 It is the example in Head First Python 这是Head First Python中的示例

james = []
def sanitize(time_string):
    if '-' in time_string:
        splitter = '-'
    elif ':' in time_string:
        splitter = '-'        
    else:
        splitter = ','
    (mins, secs) = time_string.split(splitter)
    return(mins + '.' + secs)

with open('james.txt', 'r') as jaf:
    data = jaf.readline()
    james_data = data.strip().split(',')

for each_item in james_data:
    james.append(sanitize(each_item))
sort(james)
print(james)

I'm pretty sure the second if should have 我很确定第二个应该

elif ':' in time_string:
    splitter = ':'    

Basically it looks for strings of type: min:sec or min-sec or min,sec and tries to convert them into min.sec 基本上,它将查找以下类型的字符串:min:sec或min-sec或min,sec,然后尝试将其转换为min.sec

However currently on anything other then min-sec it will fail because split will not have anything valid to work on. 但是当前除了min-sec以外的其他任何时间都将失败,因为split没有有效的工作方法。

So it looks like it will work only on a csv file with pairs like: 因此,看起来它仅适用于成对的csv文件,例如:

 min-sec, min-sec, min-sec,

in the first line 在第一行

If you fix the second 'if' it will also work on min:sec.. but it should also handle other tokens that don't have either : or - maybe just return them as is? 如果您修复了第二个“如果”,它也将在min:sec上运行。.但是它还应该处理其他没有:或-可能只是按原样返回它们的令牌?

It will also fail on values such as <???>-<????>-<???> with too many values to unpack 对于诸如<???>-<????>-<???>

Sanitize is looking for a string to split its input once it decides on a splitter it tries to split the string using it then rebuild it.. Sanitize在确定要尝试使用它拆分字符串然后重新构建的拆分器之后,正在寻找一个字符串以拆分其输入。

However if the splitter appears more then once it will fail since there will be too may values to unpack. 但是,如果拆分器显示的次数更多,则一旦分解器将失败,因为可能会有太多的值需要解压缩。 And the default splitter is , which is the only character that can't possibly appear in this text ever 默认的分隔符是,这是该文本中唯一不可能出现的字符

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM