【问题标题】:TypeError: unsupported operand type(s) for +: 'NoneType' and 'int' in while loop类型错误:+ 不支持的操作数类型:while 循环中的“NoneType”和“int”
【发布时间】:2017-05-26 15:18:18
【问题描述】:

有一个函数可以将字符串与列表中的项目进行匹配,如果匹配,则返回列表项的索引号。如下:

def get_int(get_wd, get_list):
   for i, j in enumerate(get_list):
       if j == get_wd:
         get_i = i
         return get_i

并且在主函数中有一个while循环来获取上述函数的返回整数:

get_wd = []
x = 0
candi = []

while len(li_a) > 0:
    iter_a = iter(li_a)
    srh_time = len(li_a)
    while srh_time > 0:
        temp = next(iter_a)
        if temp in li_words:
            candi.append(temp)
        else:
            pass
        srh_time = srh_time - 1
    max_len = max(len(s) for s in candi)
    extr_wd = list(set(s for s in candi if len(s) == max_len))
    pos = get_int(extr_wd, li_a) ##Calling the function##
    get_wd.append(extr_wd)
    li_a = li_a[pos + 1:]

我收到此错误消息:

>> li_a = li_a[pos + 1:]
>> TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

对我所缺少的有什么建议吗?

【问题讨论】:

  • pos 不等于任何东西,您在上面编写的函数没有返回任何内容,因此您分配给它的变量是NoneType。此外,您的原始功能中不需要get_i。只需返回i,if j == get_wd:
  • 我之前也尝试过,但仍然有相同的信息。 :(

标签: python python-2.7 while-loop nonetype


【解决方案1】:

我认为 get_int 期望 str 或 int 作为第一个 list 作为第二个参数,但 pos = get_int(extr_wd, li_a) 这里两个参数都是 list,你应该解决这个问题。

您可以使用.index 来查找索引

重构get_int方法:

def get_int(get_wd, get_list):
     try:
         return get_list.index(get_wd)
     except ValueError:
         return -1 # not found

【讨论】:

    猜你喜欢
    • 2014-03-16
    • 2020-08-26
    • 1970-01-01
    • 1970-01-01
    • 2023-02-12
    • 1970-01-01
    • 2019-08-22
    相关资源
    最近更新 更多