我想编写一段代码,打印出在给定列表中出现两次的数字的值,但它们不允许我们在 python 上使用内置函数。如果不使用枚举,我该如何编写它?
def find_second_occurrence(xs,v):
count = 0
value = None
for i, x in enumerate(xs):
if v == x:
count += 1
if count == 2:
return i
if (count < 2):
return value
最佳答案
enumerate(sequence)
与以下形式的构造非常相似:
for i in range(len(sequence)):
# get sequence[i] and return i and sequence[i] for all i's
因此,在您的代码中,可以通过以下方式完全替换 enumerate
:
for i in range(len(xs)):
x = xs[i]
if v == x:
count += 1
if count == 2:
return i
或者,不分配给 x
名称来临时保存序列项:
for i in range(len(xs)):
if v == xs[i]:
count += 1
if count == 2:
return i
创建一个 my_enumerate
函数也相当简单:
def my_enumerate(sequence, start=0):
for i in range(len(sequence)):
yield start+i, sequence[i]
start
也被定义为与 enumerate
中使用的匹配,并获取默认值 0
。
您可以创建一个列表(生成器理解类似于 yield
ing)理解并返回它,而不是使用 yield
ing 值(如果这对您来说很神秘) :
def my_enumerate(sequence, start=0):
return [(start+i, sequence[i]) for i in range(len(sequence))]
关于python - 如何制作功能类似于枚举而不实际使用枚举的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39949783/