What's the most concise way to return every fourth number in the sublists, treating all the number lists as one list?
A = [ ['a',[1,2,3]], ['b',[4,5]], ['c',[6,7,8,9,10]] ]
I want the result to look like this, when printing list A:
[ ['a',[1]], ['b',[5]], ['c',[9]] ]
I can see how this is similar to splicing a single list, in which I'd use something like [::4]. I'm guessing I have to use that here along with something else, treating the number lists as one list.
I'd use itertools.count()
, which is a handy generator which returns increasing numbers. Using that, it's almost the same as the question you originally asked, still using a nested list comprehension:
>>> from itertools import count
>>> c = count()
>>> B = [[let, [n for n in nums if next(c) % 4 == 0]] for let, nums in A]
>>> B
[['a', [1]], ['b', [5]], ['c', [9]]]
which works because the first time next(c)
is called, it gives 0, 0 % 4 == 0 so we keep n
, the next time we get 1 so we don't keep it, etc.
[Answer to original question about removing even elements:]
You can nest list comprehensions:
>>> A = [['a',[1,2,3]], ['b',[4,5]], ['c',[6,7,8,9,10]]]
>>> B = [[letter, [n for n in nums if n % 2 != 0]] for letter, nums in A]
>>> B
[['a', [1, 3]], ['b', [5]], ['c', [7, 9]]]
You could do a list comprehension! list = [x[::2] for x in A]
Something a little closer to what you wrote would be:
list =[[x[0], x[1][::2]] for x in a]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.