Python - Way to distinguish between item index in a list and item's contents in a FOR loop?
For instance, if I wanted to cycle through a list and perform some operation on all but the final list entry, I could do this:
z = [1,2,3,4,2]
for item in z:
if item != z[-1]:
print z.index(item)
But instead of getting the output "...0 1 2 3," I'd get "...0 2 3."开发者_StackOverflow社区
Is there a way to perform an operation on all but the last item in a list (when there are IDENTICAL items in the list) without using a "for x in range (len(list) - 1)" sort of solution? I.e., I want to keep using "for item in list."
Many thanks!
Use a slice:
for item in z[:-1]:
# do something
you could use:
for index, item in enumerate(z):
if index != len(z)-1:
print index
for index, item in enumerate(your_list):
do_something
[z.foo() for z in z[:-1]
def all_but_last(iterable):
iterable= iter(iterable)
try: previous= iterable.next()
except StopIteration: return
for item in iterable:
yield previous
previous= item
Put it in a module and use it wherever you need it.
In your case, you'd do:
for item in all_but_last(z):
精彩评论