How about you go about using slightly different logic if you want to persist the items:
predRange = [x for x in range(0,len(myList)) if predicate(x)]
if len(predRange) > 0:
#hey look, it's already persisted in predRange!
문제
Given the following if-statement:
if any(predicate(y) for y in range(0,len(myList))):
I am trying to keep the 'y' variable for follow-on actions, like so:
if any(predicate(y) for y in range(0,len(myList))):
#DO STUFF WITH myList[y]
Unfortunately, this results in the following error:
NameError: global name 'y' is not defined
Short of trying to replicate the any() functionality with several nested loops, I cannot think of a way to persist the 'y' variable and am unable to find anything closely related on this site. Is this even possible?
해결책 2
How about you go about using slightly different logic if you want to persist the items:
predRange = [x for x in range(0,len(myList)) if predicate(x)]
if len(predRange) > 0:
#hey look, it's already persisted in predRange!
다른 팁
I'd write it this way:
for y, myItem in enumerate(myList):
if predicate(y):
#DO STUFF WITH myList[y]
break