In python we can
a,b = tuple_with_two_items
a,b,c = tuple_with_three_items
Can we have something like
a,b,c = tuple_with_two_or_three_items
, so that when there are 3 items in the tuple, all a,b,c
have values, while when there are only 2 items, c
will take None
?
Note: grammarly I know this does not work, I'm looking for some one-liner quick work-around.
The closest would be:
a, b, *c = tuple_with_two_or_three_items
c
will be a list of all the items after the first 2. If there are only 2 items, c
will be empty, otherwise it will be contain the third value (and more if there are more than 3).
This would give you None
for c
:
a, b, c, *_ = *tuple_with_two_or_three_items, None
Or with Python 3.10:
match tuple_with_two_or_three_items:
case a, b, c:
pass
case a, b:
c = None
You could write a function to pad the size of a tuple:
def pad_tuple(items, n, fill=None):
if len(items) < n:
return items + (fill,)*(n-len(items))
return items
Then use it like this:
a, b, c = pad_tuple(tuple_with_two_or_three_items, 3)
(but an if-statement would probably be easier)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.