TypeError:list indices必须是整数或切片,而不是str“计算字符串”

时间:2017-06-18 19:58:53

标签: python arrays list python-3.5

我正在尝试计算输入字符串中连续的d或D的数量。

但它没有使用此代码,我不知道我在哪里犯了错误。

请解决此问题。

up = 0
down = 0
down_count = 0

test = input("Enter test cases: ")

for i in test:
    s = input("Enter the string: ")
    l = list(s)
    for c in l:
        if l[c] == 'u' or 'U':
            up += 1
        if l[c] == 'd' or 'D':
            down += 1
        down_count += 1

print(down_count)

错误是:

Enter test cases: 1
Enter the string: duuuuuddddduuudddd
Traceback (most recent call last):
  File "C:/Users/HAMEED/PycharmProjects/crayons/ada_and_crayons.py", line 11, in <module>
    if l[c] == 'u' or 'U':
TypeError: list indices must be integers or slices, not str

感谢。

3 个答案:

答案 0 :(得分:0)

Python for循环实际上是for-each。 c已经是列表中的元素,而不是索引。

另请注意,or并非如此;你需要每次都明确地与元素进行比较。

for c in l:
    if c == 'u' or c == 'U':
        ...

答案 1 :(得分:0)

顺便说一句,您的代码有更多问题。回到你的问题:

替换代码的这一部分

    for c in l:
        if l[c] == 'u' or 'U':
            up += 1
        if l[c] == 'd' or 'D':
            down += 1
        down_count += 1

用这个:

    for c in l:
        if c.lower() == 'u':
            up += 1
        if c.lower() == 'd':
            down += 1
        down_count += 1

解释:

  1. c本身是字符for c in l:,其中l是字符列表);它不是一个索引。

  2. c.lower()将字母转换为小字母,因此您只需将其与小写字母进行比较。

  3. 但是 - 正如我告诉你的那样 - 你的代码有更多问题。

答案 2 :(得分:0)

(你的代码中有足够多余的命令用于你的目标,所以我把它们扔掉了。)

您只想计算连续d(或D)个字母的。一种方法(不是非常Pythonic,但你是初学者)是这样的:

当前信件为down_count(或d)时,您会增加D,但只有前一个字母不是 d才会增加 (或D)。

所以我介绍了新的布尔(逻辑)变量prev_d,用于测试前一个字符是d(或D)。对于每次迭代,我都会将此值设置为TrueFalse),因为它将在 next 迭代中使用:

down_count = 0
prev_d     = False                  # Starting with no previous 'd' (or 'D')

s = input("Enter the string: ")

for c in s:
    if c.lower() == 'd':
        if not prev_d:              # This is the same as "if prev_d == False:"
            down_count += 1
        prev_d = True               # For next iteration: the previous char WAS 'd' or 'D'
    else:
        prev_d = False              # For next iteration: the prev. char was NOT 'd' or 'D'

print(down_count)