You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何筛选列表中值为0或1的成员并打印?

解决Python列表输出指定值成员的问题

直接输出元素值

你的List_of_things列表里的元素本身都是0或1,直接打印列表就能得到所有符合条件的元素:

print(List_of_things)
# 输出结果:[1, 1, 0, 0]

如果需要筛选特定值的元素,用列表推导式即可:

  • 筛选值为1的元素:
print([item for item in List_of_things if item == 1])
# 输出结果:[1, 1]
  • 筛选值为0的元素:
print([item for item in List_of_things if item == 0])
# 输出结果:[0, 0]

输出对应事物名称(更贴合需求)

你定义的dog、cat等变量名才是代表具体事物的标识,原列表只存储了它们的数值。如果要输出数值对应的事物名称,建议用字典来关联名称和数值:

# 用字典存储事物名称与对应值
things = {
    'dog': 1,
    'cat': 1,
    'rose': 0,
    'violet': 0
}

# 输出值为1的事物名称
print([name for name, val in things.items() if val == 1])
# 输出结果:['dog', 'cat']

# 输出值为0的事物名称
print([name for name, val in things.items() if val == 0])
# 输出结果:['rose', 'violet']

# 输出所有值为0或1的事物名称(此例中全部符合)
print([name for name, val in things.items() if val in (0, 1)])
# 输出结果:['dog', 'cat', 'rose', 'violet']

内容的提问来源于stack exchange,提问作者user22309639

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 08:36:57