简体   繁体   中英

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

int_list = list(range(1000))  # list [0, 1, 2, 3, 4, ..., 999]

Now I want to select every nth element from this list. Assume n to be rational. Here: n = 7/3 = 2.333...

The size of the new list should therefore be around 42,85% (1/n) of the original one. But I don't want the elements to be selected randomly. The gap between the selected elements should be similar, but doesn't need to be always exactly the same.

The result may differ by your algorithm used and the algorithm is up to you as long as it fulfils the requirements. But to answer the comment, here is an example of what the result could look like:

int_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
out_list = [0, 2, 4, 8, 10]

The size of out_list is 45.4545...% of the int_list , which isn't 42,85%, but it's the nearest it could get.

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, ie, instead of i // 3 do a[i // 3] .

A rather generic approach where the list doesn't have to consist of the int range and where the rational value could even be less than one:

N = 7
D = 3

k = 0
result = []
for i in int_list:
    k += D
    while k >= N:
        result.append(i)
        k -= N

A naive take would be

from math import floor

def every_n(lst: list, n: int) -> list:
    l = [] 
    i = 0 
    while i < len(lst): 
        l.append(lst[floor(i)]) 
        i += n 
    return l
>>> every_n(range(1000), 7/3)
[0, 2, 4, 7, 9, 11, 14, 16, 18, 21, 23, 25, 28, 30, 32, 35, ..., 991, 994, 996, 998]

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM