开发者

'else' statement in list comprehensions

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.


I think you want:

final = [variable] if isinstance(variable, str) else list(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]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜