‘否则’列表推导式中的语句
我有一个变量,可以是字符串或元组(我提前不知道),我需要将其作为列表使用。
本质上,我想将以下内容转换为列表理解。
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我想你想要:
I think you want:
您只需要稍微重新安排一下即可。
或者也许我误解了而你真的想要
You just need to rearrange it a bit.
Or maybe I misunderstood and you really want