gpt4 book ai didi

Python 内联 if 语句

转载 作者:行者123 更新时间:2023-11-28 22:27:08 30 4
gpt4 key购买 nike

有人可以帮我解决以下语法或告诉我是否可行吗?因为我要修改 if ... else ... 条件。我不想在列表中添加重复的值,但我收到了 KeyError

其实我不太熟悉这种说法:

twins[value] = twins[value] + [box] if value in twins else [box]

这到底是什么意思?

示例代码

#dictionary
twins = dict()
#iterate unitlist
for unit in unitlist:
#finding each twin in the unit
for box in unit:
value = values[box]
if len(value) == 2:
twins[value] = twins[value] + [box] if value in twins else [box]

我修改了条件

#dictionary
twins = dict()
#iterate unitlist
for unit in unitlist:
#finding each twin in the unit
for box in unit:
value = values[box]
if len(value) == 2:
if value not in twins:
twins[value] = twins[value] + [box]

最佳答案

这个

twins[value] = twins[value] + [box] if value in twins else [box]

在功能上等同于此:

if value in twins:
tmp = twins[value] + [box]
else:
tmp = [box]
twins[value] = tmp

关于Python 内联 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44215291/

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