Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 views
in Technique[技术] by (71.8m points)

python - how do I iterate only once per function call

I have a list of things I want to iterate over and return each of them only once per function call.

What I've tried:


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

It's saying code unreachable at the index += 1 part. The output I want is zza the first time I call func(), then zzb, then zzc, etc.

Appreciate the help.

EDIT: I've found this answer to work well and easily readable:

index = -1


def randy():
    global index
    index += 1
    return result[index]
question from:https://stackoverflow.com/questions/65947910/how-do-i-iterate-only-once-per-function-call

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In c++ there is an operator that will increment a variable with ++i incrementing before evaluation and i++ after evaluation

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

so the function you want is

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

the := operator is new in python 3.8

so

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())

prints

zza
zzb
zzc
zzd

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

Just Browsing Browsing

[2] html - How to create even cell spacing within a

1.4m articles

1.4m replys

5 comments

56.9k users

...