Python 3.x 索引超出范围后如何返回值
我正试着做一个测试,但我有问题。我有一个for循环,在每次尝试失败后更新索引调用,但是当我的值太高时,如果它超出范围,它不会返回值,而是会抛出一个索引超出范围错误Python 3.x 索引超出范围后如何返回值,python-3.x,Python 3.x,我正试着做一个测试,但我有问题。我有一个for循环,在每次尝试失败后更新索引调用,但是当我的值太高时,如果它超出范围,它不会返回值,而是会抛出一个索引超出范围错误 class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: numneeded = target - nums[0] for number in nums: x = 1
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
numneeded = target - nums[0]
for number in nums:
x = 1
while x <= len(nums):
y = 0
if nums[y] == target / 2:
y += 1
if nums[x] == -1:
return(y, x)
if nums[x] == numneeded:
return (0, x)
else: x += 1
return(y, x)
类解决方案:
def twoSum(self,nums:List[int],target:int)->List[int]:
numneeded=target-nums[0]
对于NUM中的数字:
x=1
当x时,这将简单地传递为twoSum:
class Solution:
def twoSum(self, nums, target):
indices = {}
for index, num in enumerate(nums):
if target - num in indices:
return indices[target - num], index
indices[num] = index
对于您的问题,在python 3中,我们将使用/
而不是通常用于python 2的/
:
from typing import List
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
numneeded = target - nums[0]
for number in nums:
x = 1
while x <= len(nums):
y = 0
if nums[y] == target // 2:
y += 1
if nums[x] == -1:
return(y, x)
if nums[x] == numneeded:
return (0, x)
else:
x += 1
return(y, x)
print(Solution().twoSum(nums=[2, 7, 11, 15], target=9))
输入导入列表中的
类解决方案:
def twoSum(self,nums:List[int],target:int)->List[int]:
numneeded=target-nums[0]
对于NUM中的数字:
x=1
虽然x是好的,但我对这个还是新手,所以enumerate到底做什么呢?返回指数不是返回实际的数字,而不是位置吗?