0

What's wrong with this python snippet:

for zhszam in pontok.keys():
    s = 0
    for p in pontok[zhszam]:
        if p.isdigit():
            s += int(p)
            print s
    pontok[zhszam] = s
return pontok

where pontok is {1: ['10', ' 5', ' 3', ' 10', ' 7'], 2: ['10', ' 5', ' 3', ' 10']}. It gives the following wrong output somehow:

10
10
{1: 10, 2: 10}

While the values should be the sum of the numbers.

Thanks in advance!

4

3 回答 3

5

除了第一个字符串之外,每个字符串'10'都有一个前导空格,它不是数字。因此它根本没有被处理。

尝试:

for p in pontok[zhszam]:
    p = p.strip()
    # ...
于 2013-06-14T21:27:00.557 回答
2

你不应该使用str.isdigit它,它很容易坏掉。最好将 try-except 块与int().

>>> dic = {1: ['10', ' 5', ' 3', ' 10', ' 7'], 2: ['10', ' 5', ' 3', ' 10']}
for k,v in dic.iteritems():
    s = 0
    for x in v:
        try:
            s += int(x)     #raises Error if the item is not a valid number
        except:              
            pass            #leave the item as it is if an error was thrown
    dic[k] = s 
...     
>>> dic
{1: 35, 2: 28}
于 2013-06-14T21:30:37.060 回答
1

我宁愿发表评论也不愿将此作为答案,但我还没有代表。这个问题将帮助您去除那些前导空格:Python remove all whitespace in a string

于 2013-06-14T21:30:32.950 回答