3

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?

2
  • 3
    The split part looks pretty good, why bother putting it into separate variables? Is it only going to be 2 or 3? Commented Jul 3, 2012 at 14:37
  • 3
    How are you going to access c if you (depending on the input) don't create it? Commented Jul 3, 2012 at 14:38

2 Answers 2

9

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)
Sign up to request clarification or add additional context in comments.

5 Comments

@larsmans: Hey, you are not the only one with all the tricks. :-P I may admit to having been reminded though...
Actually, adding a single None may be better in this case, since the list must have at least two elements. But you already have my +1.
@larsmans: This is more generic; the OP code indeed checks for 2 or 3, but perhaps he wanted 0 or 1 too. :-)
@idealistikz: Please, could you make that a new question instead of changing this one after accepting it? That's a pretty substantive change in the problem requirements, in my opinion.
1

Just an addendum to Martjin. Turned it into a function to show why you might use it. You can do dynamic sentinels using

def store(mylist,expsiz = 10, dflt = None):
    return mylist + [dflt]*(expsiz-len(mylist))

>>> mylist = [1,2,5]
>>> fixedlen = store(mylist)
>>> print fixedlen
[1,2,5,None,None,None,None,None,None,None]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.