tags:

views:

420

answers:

5

Is there a "pythonic" way of getting only certain values from a list, similar to this perl code:

my ($one,$four,$ten) = line.split(/,/)[1,4,10]
+5  A: 
lst = line.split(',')
one, four, ten = lst[1], lst[4], lst[10]
SilentGhost
I think you misunderstood the question
Idan K
@Idan: may be I have, am I not supposed to get 2nd, 5th and 11th elements of the new list?
SilentGhost
@Idan K: There's no requirement that the "Pythonic" version be a single expression like the Perl version.
Greg Hewgill
The idea that less lines of code == better code is incorrect
Lennart Regebro
cool, thanks!!!
ennuikiller
Why the downvote?
SilentGhost
+1  A: 

As far as I know there isn't you could write your own function though.

wich
+6  A: 

I think you are looking for operator.itemgetter:

import operator
line=','.join(map(str,range(11)))
print(line)
# 0,1,2,3,4,5,6,7,8,9,10
alist=line.split(',')
print(alist)
# ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
one,four,ten=operator.itemgetter(1,4,10)(alist)
print(one,four,ten)
# ('1', '4', '10')
unutbu
This is a lot of code ...
Hamish Grubijan
Not really. If you take out the demonstrative code it can look like this: one,four,ten=operator.itemgetter(1,4,10)(line.split(','))
Eric Palakovich Carr
I like this one alot! thanks!
ennuikiller
+1  A: 

Yes:

data = line.split(',')
one, four, ten = data[1], data[4], data[10]

You can also use itemgetter, but I prefer the code above, it's clearer, and clarity == good code.

Lennart Regebro
+3  A: 

Try operator.itemgetter (available in python 2.4 or newer):

Return a callable object that fetches item from its operand using the operand’s _getitem_() method. If multiple items are specified, returns a tuple of lookup values.

>>> from operator import itemgetter
>>> line = ','.join(map(str, range(11)))
>>> line
'0,1,2,3,4,5,6,7,8,9,10'
>>> a, b, c = itemgetter(1, 4, 10)(line.split(','))
>>> a, b, c
('1', '4', '10')

Condensed:

>>> # my ($one,$four,$ten) = line.split(/,/)[1,4,10]
>>> from operator import itemgetter
>>> (one, four, ten) = itemgetter(1, 4, 10)(line.split(','))
The MYYN
The right import is `from operator import itemgetter`
Roberto Bonvallet
thx, edited ...
The MYYN