‘否则’列表推导式中的语句

发布于 2024-09-24 20:49:16 字数 668 浏览 1 评论 0原文

我有一个变量,可以是字符串或元组(我提前不知道),我需要将其作为列表使用。

本质上,我想将以下内容转换为列表理解。

variable = 'id'
final = []
if isinstance(variable, str):
    final.append(variable)
elif isinstance(variable, tuple):
    final = list(variable)

我正在思考以下内容(这给了我一个语法错误)。

final = [var for var in variable if isinstance(variable, tuple) else variable]

我见过这个问题但它不一样,因为提问者可以在最后使用 for 循环;我的仅适用于元组。

注意:如果我使用 isinstance(variable, list) 以及 tuple ,我希望列表理解能够工作。

I've got a variable that could either be a string or a tuple (I don't know ahead of time) and I need to work with it as a list.

Essentially, I want to transform the following into a list comprehension.

variable = 'id'
final = []
if isinstance(variable, str):
    final.append(variable)
elif isinstance(variable, tuple):
    final = list(variable)

I was thinking something along the lines of the following (which gives me a syntax error).

final = [var for var in variable if isinstance(variable, tuple) else variable]

I've seen this question but it's not the same because the asker could use the for loop at the end; mine only applies if it's a tuple.

NOTE: I would like the list comprehension to work if I use isinstance(variable, list) as well as the tuple one.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

微凉徒眸意 2024-10-01 20:49:16

我想你想要:

final = [variable] if isinstance(variable, str) else list(variable)

I think you want:

final = [variable] if isinstance(variable, str) else list(variable)
烟沫凡尘 2024-10-01 20:49:16

您只需要稍微重新安排一下即可。

final = [var if isinstance(variable, tuple) else variable for var in variable]

或者也许我误解了而你真的想要

final = variable if not isinstance(variable, tuple) else [var for var in variable]

You just need to rearrange it a bit.

final = [var if isinstance(variable, tuple) else variable for var in variable]

Or maybe I misunderstood and you really want

final = variable if not isinstance(variable, tuple) else [var for var in variable]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文