问题描述:

How may I access to a tuple initialized within a if/else statement without using tuple() and list() functions?

I have this code:

if x > y:

foo = (a, b)

elif y > x:

foo = (b, a)

(tmp1, tmp2) = foo

but python returns: UnboundLocalError: local variable 'foo' referenced before assignment.

In other programming languages you can initialize the variable outside the statement, but what about this case?

Important: I need to work with a tuple, not a list.

Update: I don't need the case x == y, so I've changed my code adding a further condition:

foo = None

if x > y:

foo = (a, b)

elif y > x:

foo = (b, a)

if foo != None:

(tmp1, tmp2) = foo

Update2: Or, similarly:

if x > y:

foo = (a, b)

elif y > x:

foo = (b, a)

else:

foo = ()

if len(foo) > 0:

(tmp1, tmp2) = foo

网友答案:

Python does not have block scope. And the tuple and list functions are irrelevant here, as is the choice of which type you use.

The only reason foo would be undefined here is because you have forgotten a condition: when x and y are equal.

网友答案:

That should work, but try explicitly declaring foo before the if-else block

x=3
y=2
a=1
b=2
foo=None #tell python foo must be reserved at this scope level
if x > y:
    foo = (a, b)
elif y > x:
    foo = (b, a)
elif y == x: #need to remember this case
    foo = (b, a)

(tmp1, tmp2) = foo
网友答案:

In a single line, assuming you forgot the case x == y in your code:

(tmp1, tmp2) = (a, b) if x > y else (b, a)

But if you want to keep your syntax, just do not forgot the == condition!

if x > y:
    foo = (a, b)
else:
    foo = (b, a)

(tmp1, tmp2) = foo

(edited after @Daniel Roseman's answer)

相关阅读:
Top