我一直在寻找一种在 Python 中创建 for 循环的方法,而无需使用“for”等词。 我想使用 def 而不是内置函数创建一个 for 循环。我基本上想从头开始创建自己的 for 循环
在python中从头开始创建len的代码示例:
def L(list): #code for len() function.
counter = 0 #uses counter and for-loop
for n in list: #to increment counter for each
counter += 1 #value in the entered list
print(counter)
非常感谢任何帮助。
答案 0 :(得分:0)
如果您不想使用 library(ggplot2)
df1<-data.frame(y=c(1,0.99,0.97,0.95,0.94,0.94,0.82,0.72,0.58,0.34,0.20,0.12,0.11,0),
time=c(3,4,7,8,10,11,13,14,15,17,20,22,23,24))
ggplot(df1, aes(time,y)) + geom_point() +
geom_smooth(method = "gam", formula = y ~ poly(x, 2),se=F)
循环,可以改用 while
循环:
for
答案 1 :(得分:0)
好的,首先,您需要了解 for
和 len
是非常不同的东西。 len() 是一个内置函数。作为一个函数,当然可以用python重新实现。只是为了方便起见。
for 是一个关键字,也是一个基本的语言特性。 这不是函数。因此,您无法重新实现它(除非您正在编辑解释器)。尽管如此你可以创建一个做同样事情的函数
这是一个使用递归的示例:
def for-loop(iterator, function):
iterator = iter(iterator) #convert given iterable to iterator if not already done
try:
value = next(iterator)
except StopIteration:
return
function(value)
return for-loop(iterator, function) #recurse
#usage example :
for-loop(range(5), lambda x: print(x))
返回
0
1
2
3
4
如果您不理解此代码,您可能想阅读有关迭代器的内容,以及 Python 的真正用途以及递归。
编辑:实际上,我开始认为这是一个很好的练习,因为它教你高级语言特性和技术,如迭代器、递归、lambda 函数……如果你想继续这个练习,你可以实现 else
(来自 for: else:
构造)