def print_factors(x):
arr = []
for i in range(1, x+1):
if x % i == 0:
arr.append(i)
for index, value in enumerate(arr, start = 1):
print(index, value)
num = 10
print_factors(num)
Output :
1 1
2 2
3 5
4 10
现在我想要具体的索引值。例子:输入3,输出为5;输入4,输出为10;
请帮忙理清我的逻辑。
如果我理解你的问题…
def get_factors(x):
arr = []
for i in range(1, x+1):
if x % i == 0:
arr.append(i)
return arr
factors = get_factors(10)
num = 4
print(num, factors[num-1])
more sophisticated…
def get_factors(x):
return [i for i in range(1, x+1) if x % i == 0]
factors = get_factors(10)
num = 4
print(num, factors[num-1])
如果您希望能够输入索引来检查数组中的值,只需返回数组,以便您可以获得值。可以在数组中输入任意索引来获取值。
def print_factors(x):
arr = []
for i in range(1, x+1):
if x % i == 0:
arr.append(i)
#print(arr)
for index, value in enumerate(arr, start = 1):
print(index, value)
return arr
num = 10
arr = print_factors(num)
print(arr[2]) # what is index 2!
这可能是一个更好的写法。有一个函数用来构建数组,另一个函数用来打印因子和索引
def build_factors(x):
arr = []
for i in range(1, x+1):
if x % i == 0:
arr.append(i)
return arr
def print_factors(arr):
for index, value in enumerate(arr, start = 1):
print(index, value)
num = 10
arr_factors = build_factors(num)
print_factors(arr_factors)
print(arr_factors[2]) # what is index 2!