[英]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.