在带有名称的循环中创建函数取决于可迭代对象

Creating functions in a loop with names depends on the iterable

我的目标:用函数 ni.

从数字 x 中得到位置 i 的数字

例如:( i = 3 和 x = 12345 ) => n3(12345) == 4.

我的任务围绕着很多数字操作,我最多可以处理 10**24 个数字。

我想在一个 for 循环中一次性创建 24 个函数:n1 - n2 .. n24 :

for i in range(1,25):
    def n`i`(x):
        return int(str(x)[i])

一般来说,如何从数据列表中自动创建函数?

我对编码还是个新手,非常感谢您的建议!

试试这个

#example data
import random
ranges=25
n = 10**24
number = [random.randint(n,n*10) for x in range(ranges)]

def ni(x,i):
    return int(str(x)[i])

#print out all data and get the digit in the position i
for i in range(25):
    print(ni(number[i],i))

#print a data and get all digit
for i in range(25):
    print(ni(number[1],i))

#print a data and get the digit in the position i
ni(number[9],3)
ni(number[7],2)
ni(number[8],7)

正是您所要求的。

for i in range(1, 10):
    def fn(x):
        return int(str(x)[i])
    
    globals()[f"n{i}"] = fn  # update global variables dictionary

#use them like
n3(123456)

但我建议定义一个接受两个参数的函数并使用它

def ni(i,x):
   return int(str(x)[i])

ni(3, 123456)