Suppose I have a string of integers separated by commas of variable length. What is the best way to split the string and store the integers into variables?
Currently, I have the following.
input = sys.argv[1]
mylist = [int(x) for x in input.split(',')]
if len(mylist) == 2: a, b = mylist
else: a, b, c = mylist
Is there a more efficient way of doing this?
Add sentinels, then limit the list to 3 elements:
a, b, c = (mylist + [None] * 3)[:3]
Now a, b and c are at the very least set to None, and if the number of items is more than three only the first three values are used.
Demo:
>>> mylist = [1, 2]
>>> a, b, c = (mylist + [None] * 3)[:3]
>>> print a, b, c
1 2 None
>>> mylist = [1, 2, 3, 4]
>>> a, b, c = (mylist + [None] * 3)[:3]
>>> print a, b, c
1 2 3
If you need at least 2 elements, use fewer None values and catch ValueError:
try:
a, b, c = (mylist + [None])[:3]
except ValueError:
print "You mast specify at least 2 values"
sys.exit(1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With