如何每次函数调用只迭代一次



我有一个列表,我想迭代遍历,每个函数调用只返回一次。

我试过了:


tl = """
zza,zzb,zzc,zzd,zze,zzf,zzg,zzh,zzi,zzj,zzk,zzl,zzm,zzn,zzo,zzp,zzq,zzr,zzs,zzt,zzu,zzv,zzw,zzx,zzy,zzz
"""
# convert each string into list
result = [x.strip() for x in tl.split(",")]
index = 0
def func():
return result[index]
index += 1

表示在index += 1部分代码不可达。第一次调用func()时,我想要的输出是zza,然后是zzb,然后是zzc,等等。

谢谢你的帮助。

编辑:我发现这个答案工作得很好,很容易读:

# list of elements seperated by a comma
tl = """
zza,zzb,zzc,zzd,zze,zzf,zzg,zzh,zzi,zzj,zzk,zzl,zzm,zzn,zzo,zzp,zzq,zzr,zzs,zzt,zzu,zzv,zzw,zzx,zzy,zzz
"""
# split each string by comma to get a list
result = [x.strip() for x in tl.split(",")]
# initialize the object
iterator_obj = iter(result)
print(next(iterator_obj))
print(next(iterator_obj))
print(next(iterator_obj))

输出:

zza
zzb
zzc

在c++中有一个操作符,它将对变量进行递增,++i在求值前递增,i++在求值后递增

(i:=i+1) #same as ++i (increment, then return new value)
(i:=i+1)-1 #same as i++ (return the incremented value -1)

你想要的函数是

def func():
global index
return result[(index := index+1)-1]

:=操作符是python 3.8中新增的

tl = """
zza,zzb,zzc,zzd,zze,zzf,zzg,zzh,zzi,zzj,zzk,zzl,zzm,zzn,zzo,zzp,zzq,zzr,zzs,zzt,zzu,zzv,zzw,zzx,zzy,zzz
"""
# convert each string into list
result = [x.strip() for x in tl.split(",")]
index = 0
def func():
global index
return result[(index := index + 1) - 1]
print(func())
print(func())
print(func())
print(func())

打印

zza
zzb
zzc
zzd

因为return语句退出了函数,在此之后的任何语句都不可访问。对代码的快速修复:

tl = """
zza,zzb,zzc,zzd,zze,zzf,zzg,zzh,zzi,zzj,zzk,zzl,zzm,zzn,zzo,zzp,zzq,zzr,zzs,zzt,zzu,zzv,zzw,zzx,zzy,zzz
"""
# convert each string into list
result = [x.strip() for x in tl.split(",")]
next_index = 0
def func():
global next_index
next_index += 1
return result[next_index-1]

顺便说一句,你的函数的行为就像内置的next。如果你不想重新发明轮子:

# convert each string into iterator
result = (x.strip() for x in tl.split(","))
# next(result) will get to the next item on the list

如果您希望每次函数调用只能返回字符串中的一项,则需要使用生成器:

def func(items):
string_list = items.split(",")
for i in range(len(string_list)):
yield string_list[i]
tl = """
zza,zzb,zzc,zzd,zze,zzf,zzg,zzh,zzi,zzj,zzk,zzl,zzm,zzn,zzo,zzp,zzq,zzr,zzs,zzt,zzu,zzv,zzw,zzx,zzy,zzz
"""
item = func(tl)

按顺序取出一个值,使用

next(item) # zza
next(item) # zzb
...

每次调用next,都会返回一个新值。

作为题外话,return语句之后的任何内容都不会运行,这就是为什么您的index += 1不起作用。Return停止函数运行

最新更新