Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/350.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python TypeError:字符串索引必须是整数!我该怎么办_Python_Typeerror - Fatal编程技术网

Python TypeError:字符串索引必须是整数!我该怎么办

Python TypeError:字符串索引必须是整数!我该怎么办,python,typeerror,Python,Typeerror,我明白了: 计数器=计数器+dic[l[i]] TypeError:字符串索引必须是整数这太复杂了。您得到的是TypeError,因为您试图使用l的字符索引l。但是您不需要索引到l,只需直接迭代数字字符串中的字符即可 这是您的代码的修复版本 import sys a = int(sys.argv[1]) def count_holes(n): dic = {'1':0, '2':0, '3':0, '4':1, '5':0, '6':1, '7':0, '8':2, '9':1}

我明白了: 计数器=计数器+dic[l[i]]
TypeError:字符串索引必须是整数

这太复杂了。您得到的是
TypeError
,因为您试图使用
l
的字符索引
l
。但是您不需要索引到
l
,只需直接迭代数字字符串中的字符即可

这是您的代码的修复版本

import sys
a = int(sys.argv[1])
def count_holes(n):
    dic = {'1':0, '2':0, '3':0, '4':1, '5':0, '6':1, '7':0, '8':2, '9':1}
    l = str(n)
    counter = 0
    i = 1

    for i in l:
        while i != len(l):
            counter = counter + dic[l[i]]
    print(counter)
count_holes(a)

下面是一些测试代码:

import sys

def count_holes(n):
    dic = {'1':0, '2':0, '3':0, '4':1, '5':0, '6':1, '7':0, '8':2, '9':1}
    counter = 0
    for c in str(n):
        counter += dic[c]
    return counter

a = int(sys.argv[1])
print(count_holes(a))
及其产出

for i in (12357, 4, 66, 8, 999):
    print(i, count_holes(i))

当你在l中说i时,我循环使用字符串l中的字符。所以i是一个字符串,不能用作索引。可以枚举()字符串并使用循环中的第二个变量作为索引


如果n中包含len(n),我可以看到while循环是如何退出的,但我不确定这是否就是你想要的。虽然我和len(l)是不同类型的人,所以你有自己的特点。。。这很好

你在干什么?你想要什么?那
while
循环是无限的,如果它能工作的话。它应该计算一个字符串在number
l
中有多少个洞<代码>对于l中的i表示
i
将是一个字符串。所以
当我=len(l)
始终为真,
l[i]
试图使用字符串
i
作为另一个字符串的索引
l
也许您需要整数作为索引?类似于
dic={1:0,2:0,4:0…
?答案很好。现在您可以看到整个函数体可以重写为:
返回和({'0':0,'4':1,'6':1,'8':2,'9':1}。在str(n)中为c获取(c,0))
@matthia是肯定的(尽管您的dict应该有'0':1),但我觉得这是家庭作业,OP应该练习循环,所以我不想太多地浓缩代码。这就是为什么我说“好答案”。你的答案完美地解释了如果我们想保持OPs结构,代码应该是什么样子。我忍不住添加我的解决方案(顺便说一句,增加了零号的处理)。@Matthias很公平。谢谢!
12357 0
4 1
66 2
8 2
999 3