假设待标记的列表为 lst,则可以使用以下代码实现:

lst = [1, 2, 3, 4, 5, 6, 7, 8, 9]

# 利用列表生成式和函数标记奇偶数
marked_lst = [1 if x % 2 != 0 else 2 for x in lst]

# 统计奇偶数的数量
odd_count = marked_lst.count(1)
even_count = marked_lst.count(2)

print(marked_lst)  # 输出标记后的列表
print('奇数数量:', odd_count)
print('偶数数量:', even_count)

输出结果为:

[1, 2, 1, 2, 1, 2, 1, 2, 1]
奇数数量: 5
偶数数量: 4
Python 列表奇偶数标记及统计:函数和列表生成式

原文地址: https://www.cveoy.top/t/topic/n5r3 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录