I have a list of 0s, named "variables". One of the 0s will become -1 spontaneously, and I'm trying to print the element which does. For example, this is my code:
while True:
if any(variables):
print(variables[i])
Now, obviously "i" doesn't correlate to anything, but I'd like it to represent the index of the non-zero variable in the list "variables". Should I enumerate? Is there an easy way to do this with list comprehension? Thank you!
Try
print(list(filter(lambda x: x==-1, variables)))
Do you want to get the index? Outputting the element would be equal to just writing print(-1)
print (variables.index(-1))
Printing the element would just give you -1 .
You can loop through the list:
for e in variables:
if e != 0:
# -1 found
By using print(variables.index(-1)) you can also print the spot where -1 was found.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.