python - Splicing lists within a list -


what's concise way return every fourth number in sublists, treating number lists 1 list?

a = [ ['a',[1,2,3]], ['b',[4,5]], ['c',[6,7,8,9,10]] ] 

i want result this, when printing list a:

[ ['a',[1]], ['b',[5]], ['c',[9]] ] 

i can see how similar splicing single list, in i'd use [::4]. i'm guessing have use here along else, treating number lists 1 list.

i'd use itertools.count(), handy generator returns increasing numbers. using that, it's same question asked, still using nested list comprehension:

>>> itertools import count >>> c = count() >>> b = [[let, [n n in nums if next(c) % 4 == 0]] let, nums in a] >>> b [['a', [1]], ['b', [5]], ['c', [9]]] 

which works because first time next(c) called, gives 0, 0 % 4 == 0 keep n, next time 1 don't keep it, etc.


[answer original question removing elements:]

you can nest list comprehensions:

>>> = [['a',[1,2,3]], ['b',[4,5]], ['c',[6,7,8,9,10]]] >>> b = [[letter, [n n in nums if n % 2 != 0]] letter, nums in a] >>> b [['a', [1, 3]], ['b', [5]], ['c', [7, 9]]] 

Comments

Popular posts from this blog

c++ - OpenCV Error: Assertion failed <scn == 3 ::scn == 4> in unknown function, -

php - render data via PDO::FETCH_FUNC vs loop -

The canvas has been tainted by cross-origin data in chrome only -