如何在 python 的 for 循环中同时检查两个条件?

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

我在标签“0”或“1”中有一个单词列表。 我想访问并计算我的列表中有多少单词以 -a 结尾,其标签为 1,有多少单词以 -o 结尾,其标签为 0。我的想法是使用 enumerate as 访问列表的第一个和第二个元素下面,但这不起作用。我该怎么做?

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

obj1 = enumerate(ts)

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

时间:O(N) Space: O(1) 解决方案

如果保证列表长度为偶数,可以

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

您需要检查枚举的作用。它不是你认为的那样。我可以通过查看您的代码来判断这一点

如果我没理解错的话,你有一个混合列表,其中奇数元素是标签,成对元素是单词。当你满足以下两个条件之一时,你想操作一些代码(计数和更多):

  1. label =“0”,单词以“o”结尾
  2. label = “1”,单词以“a”结尾

关注@Olvin Roght的建议(谁在您的问题下发表了评论):

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

你为什么不尝试这样的事情呢?如果不需要,使用 enumerate 是没有意义的;只需尝试一个简单的 for 循环。

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)

您可以将生成器传递给 sum() 函数来计算两个条件的数量:

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

如果你很在意两次切片列表带来的内存消耗,你可以使用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)))

或者您可以使用索引 遍历列表(如果列表包含奇数个元素将抛出异常):

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