列表索引必须是整数,而不是str错误

时间:2015-10-15 02:58:06

标签: python list python-3.x syntax-error

我的小功能在这里,我试图将我的10位整数电话号码改为单词形式。它给了我一个错误。

def getWordForm(phone_num):
    cake=list(phone_num)
    print(cake)
    for v in cake:
        if cake[v] == 0:
            cake[v] = "zero "
        elif cake[v] == 1:
            cake[v] = "one "
        elif cake[v] == 2:
            cake[v] = "two "
        elif cake[v] == 3:
            cake[v] = "three "
        elif cake[v] == 4:
            cake[v] = "four "        
        elif cake[v] == 5:
            cake[v] = "five "  
        elif cake[v] == 6:
            cake[v] = "six "
        elif cake[v] == 7:
            cake[v] = "seven "
        elif cake[v] == 8:
            cake[v] = "eight "
        elif cake[v] == 9:
            cake[v] = "nine "

感谢大家的帮助。

2 个答案:

答案 0 :(得分:2)

您目前正在迭代list 1个字符的字符串,然后尝试找出该字符串索引处的list元素是否等于整数。我将通过用文字替换变量来说明为什么这远不是你需要做的事情:

def getWordForm('1234567890'):
    ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']=list('1234567890')
    print(['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'])
    for '1','2',etc. in ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']:
        if cake['1'] == 0:
            cake['1'] = "zero "

您必须使用整数索引list。此电话号码中的字符(恰好代表整数)也与索引无关 - 您可以在索引3处设置'9'。您也不会返回任何内容,因此您的函数将运行(如果可以的话),结束并抛弃一切。

请改为:

def getWordForm(phone_num):
    numbers = {'0':'zero', '1':'one', '2':'two', '3':'three', '4':'four',
               '5':'five', '6':'six', '7':'seven', '8':'eight', '9':'nine'}
    return ' '.join(numbers[num] for num in phone_num)

结果如预期:

>>> getWordForm('123')
'one two three'

答案 1 :(得分:0)

如果您将数字作为整数传递,则list(phone_num)是错误,因为list()需要迭代器而phone_num不是迭代器。
如果传入字符串,则使用字符cake[v]索引列表。

看起来你想要迭代索引(range())并用它的单词格式交换值,例如:

cake = list(str(phone_num)):
for v in range(len(cake)):
    if cake[v] == '0':
        cake[v] = 'zero'
    ...
return cake

您还可以使用字典查找和列表解析替换整个for: if-elif-elif-...块:

word_form = {
    '0': 'zero',
    '1': 'one',
    '2': 'two',
    '3': 'three',
    '4': 'four',
    '5': 'five',
    '6': 'six',
    '7': 'seven',
    '8': 'eight',
    '9': 'nine'
}

def getWordForm(phone_num):
    return [word_form[d] for d in str(phone_num)]

>>> getWordForm(1235554387)
['one', 'two', 'three', 'five', 'five', 'five', 'four', 'three', 'eight', 'seven']
>>> getWordForm('1235554387')
['one', 'two', 'three', 'five', 'five', 'five', 'four', 'three', 'eight', 'seven']