What does the list [x :: y] do?

Possible duplicate:
Good primer for tagging Python fragments

I have been reading a few code examples recently, and I have read quite a few sites, but I just can't get the request to give me the answer I'm looking for. If anyone could help me, I would appreciate it.

+6
source share
6 answers

He cuts

x[startAt:endBefore:skip] 

if you use skip = 2 , every other item will have a list selected, starting with startAt and ending with endBefore . [Remember: indexes live between items in a list of items]

To see this, enter

 x = range(100) 

at the python command line. Then try these things

 x[::2] x[::3] x[10:40:6] 

and see what happens.

+13
source

L[x::y] means the slice L , where x is the index to start with y is the step size. Here are some examples you can try in the interpreter.

 >>> L=range(20) >>> L [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] 

If you want every third item

 >>> L[::3] [0, 3, 6, 9, 12, 15, 18] 

Now every third element, starting with L [1]

 >>> L[1::3] [1, 4, 7, 10, 13, 16, 19] 

Now every third element, starting with L [2]

 >>> L[2::3] [2, 5, 8, 11, 14, 17] 

You can specify a negative step to go back

 >>> L[::-1] [19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0] 

You can also assign this slice, but the value should be the same length as the slice you replace

 >>> L[::3]=[0,0,0,0,0,0,0] >>> L [0, 1, 2, 0, 4, 5, 0, 7, 8, 0, 10, 11, 0, 13, 14, 0, 16, 17, 0, 19] 

Finally, you can remove every third item like this

 >>> del L[::3] >>> L [1, 2, 4, 5, 7, 8, 10, 11, 13, 14, 16, 17, 19] 
+10
source

This is the syntax for sorting lists. When you speak,

 list[a:b:c], 

a is the starting index, b is the ending index, and c is the optional step size. This will give you a list starting at index a (inclusive) and ending at select b (exclusive) in step c.

For instance,

 l = [1,2,3,4,5,6,7] 

If I say l [2: 6: 2], it will give me [3,5].

If you skip the end index, as in your question, it will take elements from the initial index (x), select every yth element until it reaches the end of the list, if y is positive and starts the list if y is negative .

eg. l [1 :: - 1] = [2,1]

l [1 :: 2] = [2,4,6]

The default step size is 1.

+2
source

This means creating a new list from x to the end with step y :

 >>> l = range(10) >>> list(l[2::2]) [2, 4, 6, 8] 
0
source

Returns a list containing each yth element of the list starting at index x.

 >>> alist = range(10) >>> alist[0::2] [0, 2, 4, 6, 8] 
0
source

This is a fragment.

[start: end: step]

Leaving any void, puts them by default, in your case it takes every element y , starting from x to the end of the list.

See: What is :: (double colon) in Python with sub-pixel sequences?

0
source

Source: https://habr.com/ru/post/906993/


All Articles