[英]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':
你为什么不尝试这样的事情? 如果不需要,使用 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))
时间:O(N) 空间:O(1) 解决方案
如果列表的长度保证是偶数,你可以
for i in range(0, len(ts), 2):
if ts[i] =='0' and ts[i + 1].endswith('o'):
# do whatever u want
您需要检查 enumerate 的作用。 它不是你认为的那样。 我可以通过查看您的代码来说明这一点
如果我理解正确,你有一个混合列表,其中奇数元素是标签,pair 元素是单词。 当你满足两个条件之一时,你想操作一些代码(计数和更多):
遵循@ 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.