python - 如何在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':
解决方案
你为什么不试试这样的东西?如果您不必使用枚举,则没有任何意义;只需尝试一个简单的 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)
推荐阅读
- c# - 找不到名为“TaskDialogIndirect DLL ComCtl32”的入口点
- angular - 如何从单选按钮角度获取检查值
- rust - 我是否需要对 Boxed 结构的子结构进行 Box 以获取堆上的所有内容?
- javascript - PHP 中的网络爬虫问题
- transactions - Kafka 事务:sendOffsetsToTransaction 比 sendRecord 慢得多
- python - 展平从 Tick Data 收集的嵌套字典,用于 2 个不同的“instrument_token”
- css - 输入类型日期在设备上看起来与 chrome 模拟器不同
- javascript - setTimeout 内的函数给出未定义的
- javascript - 如何实现“加载更多”功能以与 redux 做出反应?
- javascript - TypeError:使用 jquery.datatables.min.js 时数据未定义