Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

arrays - Default value in Python unpacking

Is there a way to have a default value if the number of values to unpack is too little compared to the variable list?

For example:

a, b, c = read_json(request)

This works if read_json returns an array of three or more variable. If it only returns two, I get an exception while assigning c. So, is there a way to set c to a default value if it can't be unpacked properly? Something like:

a, b, (c=2) = read_json(request)

Which is similar to what you do when defining a function with default arguments.

Thank you!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could try * unpacking with some post-processing:

a, b, *c = read_json(request)
c = c[0] if c else 2

This will assign a and b as normal. If c is assigned something, it will be a list with one element. If only two values were unpacked, it will be an empty list. The second statement assigns to c its first element if there is one, or the default value of 2 otherwise.

>>> a, b, *c = 1, 2, 3
>>> c = c[0] if c else 2
>>> a
1
>>> b
2
>>> c
3
>>> a, b, *c = 1, 2
>>> c = c[0] if c else 2
>>> a
1
>>> b
2
>>> c
2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...