简体   繁体   English

Python 类型错误:列表索引必须是整数或切片,而不是浮点错误

[英]Python TypeError: list indices must be integers or slices, not float Error

I am getting a TypeError: list indices must be integers or slices, not float on the fourth line of code when I run this.我得到一个 TypeError: list indices must be integers or slices, not float on the Fourth line of code 当我运行它时。 nums and nums2 are simply asking the user to provide a list of numbers that will be used to calculate the inner product in the code that I have provided. nums 和 nums2 只是要求用户提供一个数字列表,这些数字将用于计算我提供的代码中的内积。

def innerproduct(nums, nums2):
    for i in nums:
        if i in nums2:
            sum +- nums[i] * nums2[i]
    return innerproduct

I'm not sure why this error is occurring and how to resolve this issue, so any guidance would be appreciated.我不确定为什么会发生此错误以及如何解决此问题,因此不胜感激。

for i in nums means that i will store the value in nums list, not the index. for i in nums意味着i会将值存储在 nums 列表中,而不是索引中。

for example if nums = [1.5, 6.2, 0.1] then i would be 1.5 and nums[i] is throwing that error.例如,如果 nums = [1.5, 6.2, 0.1] 那么 i 将是1.5并且nums[i]会抛出该错误。

either you can do for i in range(len(nums)): and get nums[i] or just for i in nums and then sum += i instead of nums[i]要么你可以做for i in range(len(nums)):并得到nums[i]或者只是for i in nums然后 sum += i而不是nums[i]

Extending Shubham's answer,扩展 Shubham 的答案,

update your code with the below snippet and your code will work使用以下代码段更新您的代码,您的代码将起作用

def innerproduct(nums, nums2):
    sm = 0
    for i,num in enumerate(nums): # enumerate returns index of item & actual item
        if num in nums2:
            sm += num * nums2[i]
    return sm

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 “TypeError:列表索引必须是整数或切片,而不是浮点数” - “TypeError: list indices must be integers or slices, not float” TypeError:列表索引必须是整数或切片,而不是浮点型; - TypeError: list indices must be integers or slices, not float; # TypeError: 列表索引必须是整数或切片,而不是浮点数# - # TypeError: list indices must be integers or slices, not float # python错误:类型错误:列表索引必须是整数或切片,而不是列表 - python error: TypeError: list indices must be integers or slices, not list Python 错误:类型错误:列表索引必须是整数或切片,而不是 str - Python Error: TypeError: list indices must be integers or slices, not str Pyxll:TypeError 列表索引必须是整数或切片,而不是浮点数 - Pyxll:TypeError list indices must be integers or slices,not float 在最大数中出现错误 - TypeError:列表索引必须是整数或切片,而不是浮点数 - Getting error in maxium number as - TypeError: list indices must be integers or slices, not float Python3切片,TypeError:列表索引必须是整数或切片,而不是列表 - Python3 Slicing, TypeError: list indices must be integers or slices, not list Python3-TypeError:列表索引必须是整数或切片,而不是str-List - Python3 - TypeError: list indices must be integers or slices, not str - List TypeError:列表索引必须是整数或切片,而不是列表(Python) - TypeError: list indices must be integers or slices, not list (Python)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM