简体   繁体   中英

How do I check two conditions at the same time in a for loop in python?

I have a list of words in their labels '0' or '1'. I want to access and count how many words in my list are ending in -a whose label is 1 and how many words ending in -o whose label is 0. My idea was to access the first and second element of the list using enumerate as below, but that does not work. How could I do this?

ts=['0','carro','1', 'casa', '0', 'mapa','1','fantasma']

obj1 = enumerate(ts)

    for j, element in obj1:
        if j=='0' and element[-1]=='o':       

Why don't you try something like this? There's no point of using enumerate if you don't have to; just try a simple for loop.

ts=['0','carro','1', 'casa', '0', 'mapa','1','fantasma']

oand0count = 0
aand1count = 0

# Iterates from 1, 3, 5, etc.
for i in range(1, len(ts), 2):
    # Checks specified conditions
    if ts[i-1]=='0' and ts[i][-1]=='o':    
        oand0count += 1
    elif ts[i-1]=="1" and ts[i][-1]=="a":
        aand1count += 1
        
print(oand0count, aand1count) # Prints (1, 2)

You can pass generator to sum() function to calculate number of both conditions:

first = sum(a == '0' and b == 'o' for a, (*_, b) in zip(ts[::2], ts[1::2]))
second = sum(a == '1' and b == 'a' for a, (*_, b) in zip(ts[::2], ts[1::2]))

If you do really care about memory consumption caused by slicing list twice, you can use itertools.islice() :

from itertools import islice

first = sum(a == '0' and b == 'o' for a, (*_, b) in 
    zip(islice(ts, 0, None, 2), islice(ts, 1, None, 2)))
second = sum(a == '1' and b == 'a' for a, (*_, b) in 
    zip(islice(ts, 0, None, 2), islice(ts, 1, None, 2)))

Or you can iterate over list using indexes (will throw an exception if list contains odd amount of elements) :

first = sum(ts[i] == '0' and ts[i + 1][-1] == 'o' for i in range(0, len(ts), 2))
second = sum(ts[i] == '1' and ts[i + 1][-1] == 'a' for i in range(0, len(ts), 2))

Time:O(N) Space: O(1) Solution

if length of the list is guranteed to be even numbers, u can

for i in range(0, len(ts), 2):
    if ts[i] =='0' and ts[i + 1].endswith('o'):
        # do whatever u want

You need to check what enumerate does. Its not what you think it does. I can tell this by looking at your code

If I understand it correctly, you have a mixed list where the odd elements are the labels, and the pair elements are words. You want to operate some code (count and more) when you meet either of the two conditions:

  1. label = "0", word ends with "o"
  2. label = "1", word ends with "a"

Following @ Olvin Roght suggestion (who commented under your question):

for j, element in zip(ts[0::2], ts[1::2]):
    if (j == "0" and element[-1] == "o") or (j == "1" and element[-1] == "a"):
        # your code here

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM