Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python select specific elements from a list

Tags:

python

list

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] 
like image 652
ennuikiller Avatar asked Jan 25 '10 18:01

ennuikiller


People also ask

How do you select a number in a list in Python?

randrange() Method. random. randrange() method is used to generate a random number in a range, for lists, we can specify the range to be 0 to its length, and get the index, and then the corresponding value.


2 Answers

Using a list comprehension

line = '0,1,2,3,4,5,6,7,8,9,10' lst = line.split(',') one, four, ten = [lst[i] for i in [1,4,10]] 
like image 88
has2k1 Avatar answered Oct 05 '22 08:10

has2k1


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') 
like image 41
unutbu Avatar answered Oct 05 '22 09:10

unutbu