How to Get Every Nth Item from a List<T>

How can I get every nth item from a List T ?


return list.Where((x, i) => i % nStep == 0);

Pythonic way to return list of every nth item in a larger list


>>> lst = list(range(165))
>>> lst[0::10]
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160]

Note that this is around 100 times faster than looping and checking a modulus for each element:

$ python -m timeit -s "lst = list(range(1000))" "lst1 = [x for x in lst if x % 10 == 0]"
1000 loops, best of 3: 525 usec per loop
$ python -m timeit -s "lst = list(range(1000))" "lst1 = lst[0::10]"
100000 loops, best of 3: 4.02 usec per loop

Select every nth element in list, with n rational/non-integer

Scaling the range by the denominator, stepping with the numerator, and scaling back down by dividing by the denominator:

>>> [i // 3 for i in range(0, 3 * 1000, 7)]
[0, 2, 4, 7, 9, 11, 14, 16, 18, 21, 23, 25, 28, 30, 32, 35, ..., 991, 994, 996, 998]

Your example is a range, not a list. If you really do have a list, then simply use my numbers as indices, i.e., instead of i // 3 do a[i // 3].

Finding every nth element in a list

You just need lst[::n].

Example:

>>> lst=[1,2,3,4,5,6,7,8,9,10]
>>> lst[::3]
[1, 4, 7, 10]
>>>

How can I get every nth item from a List T ?


return list.Where((x, i) => i % nStep == 0);

Linq repeat every nth element for a given range within a List T

Linq is for querying, not updating. You can write linq methods that have side effects, but because of lazy enumeration and other factors, a straight for or foreach loop is preferred:

int repeat = 2;
int skip = 3;
for(int i = 0; i < list.Count && repeat > 0; i += skip)
{
list[i].MyField = 1;
repeat--;
}

Remove every nth element from the list, if the element is not equal to an element in an other list?

You can make a list comprehension to re-create l1:

l1 = ['a1', 'a2', 'a3', 'a4', 'a5', 'a6']
l2 = ['a3', 'a4']
l2s = set(l2)

l1 = [item for index,item in enumerate(l1) if (index & 1) == 0 or item in l2s]
print(l1)

Output as requested

I created l2s to make the item in l2s faster if your real l2 is very large.



Related Topics



Leave a reply



Submit