current position:Home>Python code reading (Part 50): taking elements from list intervals

Python code reading (Part 50): taking elements from list intervals

2022-01-30 21:57:55 FelixZ

Python Code reading ( The first 50 piece )_ Get elements for list interval -cover.jpg

Python Code reading collection Introduction : Why not recommend Python Beginners directly look at the project source code

The code read in this article realizes every interval in a list n The function of taking an element from a number .

The code snippet read in this article comes from 30-seconds-of-python.

every_nth

def every_nth(lst, nth):
  return lst[nth - 1::nth]

# EXAMPLES
every_nth([1, 2, 3, 4, 5, 6], 2) # [ 2, 4, 6 ]
 Copy code 

every_nth The function receives a list and the number of intervals nth, Return the value result of the list .

The function uses list slicing , Get the original list every interval nth The result of taking values of elements .

s[i:j:k] The form of s from i To j In steps of k The section of .s from i To j In steps of k The slice of is defined as all that satisfy 0 <= n < (j-i)/k The index number of x = i + n*k A sequence of items . let me put it another way , The index number is i,i+k,i+2*k,i+3*k, And so on , When reach j Stop when ( But it must not include j). When k When it is a positive value ,i and j Will be reduced to no more than len(s). When k When it's negative ,i and j Will be reduced to no more than len(s) - 1. If i or j Omitted or omitted None, They will be defined as what can be reached at one end of the list “ End ” value ( The termination value at which end depends on k The symbol of ). Please note that ,k Cannot be zero . If k by None, As if 1 Handle .

Because the index of the list is from 0 At the beginning , So the index of the first extracted number is nth-1. because j Omitted , So it will be calculated all the way to the end of the list . We use a less “ just ” Take an example of :

>>> every_nth([1, 2, 3, 4, 5, 6, 7], 2) # [ 2, 4, 6 ]
[2, 4, 6]
 Copy code 

copyright notice
author[FelixZ],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201302157532850.html

Random recommended