首页 > 解决方案 > 如何在python的for循环中同时检查两个条件?

问题描述

我在标签“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':       

标签: pythonfor-loopenumerate

解决方案


你为什么不试试这样的东西?如果您不必使用枚举,则没有任何意义;只需尝试一个简单的 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)

推荐阅读