gpt4 book ai didi

python - 在列表解析中实现三元条件运算符

转载 作者:太空狗 更新时间:2023-10-30 02:11:39 25 4
gpt4 key购买 nike

我正在尝试在列表理解中实现三元条件运算符。我是这样写的:

lst.append(dict2obj(item)) if type(item) is not in ['int'] else lst.append(item) for item in v

其中 lst 是空列表,v 是另一个包含各种元素的列表。编辑器显示它在语法上不正确。我做错了什么?

最佳答案

  • 如果你想写列表理解你错过了[, ]:
  • 没有 is not in 运算符。使用不在
  • type 函数不返回string。为什么不使用 isinstance(item, int)

[lst.append(dict2obj(item)) if not isinstance(item, int) else lst.append(item)
for item in v]

如果可能,使用简单的for 循环。它更具可读性。

for item in v:
if not isinstance(item, int)
lst.append(dict2obj(item))
else:
lst.append(item)

关于python - 在列表解析中实现三元条件运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21157103/

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