gpt4 book ai didi

python - 如何编写 DRY Python For 循环

转载 作者:行者123 更新时间:2023-12-05 09:09:41 24 4
gpt4 key购买 nike

我有一个大麻数据集,其中有一个“效果”列,我正在尝试为不包含某些效果的菌株添加一个二进制“nice_buds”列。这是代码:

nice_buds = []
undesired_effects = ["Sleepy", "Hungry", "Giggly", "Tingly", "Aroused", "Talkative"]

for row in sample["Effects"]:
if "Sleepy" not in row and "Hungry" not in row and "Giggly" not in row and "Tingly" not in row and "Aroused" not in row and "Talkative" not in row:
nice_buds.append(1)
else:
nice_buds.append(0)

sample["nice_buds"] = nice_buds

截至目前,undesired_effects 列表什么都不做,代码在提供所需输出方面运行良好。

不过我的问题是是否有更“Pythonic”或“DRY”的方式来解决这个问题......

最佳答案

您可以使用带有生成器表达式的 all() 来简化 if 语句

nice_buds = []
undesired_effects = ["Sleepy", "Hungry", "Giggly", "Tingly", "Aroused", "Talkative"]

for row in sample["Effects"]:
if all(effect not in row for effect in undesired_effects):
nice_buds.append(1)
else:
nice_buds.append(0)

sample["nice_buds"] = nice_buds

或者使用 any() 并检查是否存在效果:

nice_buds = []
undesired_effects = ["Sleepy", "Hungry", "Giggly", "Tingly", "Aroused", "Talkative"]

for row in sample["Effects"]:
if any(effect in row for effect in undesired_effects):
nice_buds.append(0)
else:
nice_buds.append(1)

sample["nice_buds"] = nice_buds

关于python - 如何编写 DRY Python For 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62208134/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com