Slicing and iteration in python

Taking part of a list or tuple is a very common operation.

n=[]
(n[]n[])

When taking multiple elements, you can use python's own slice (slice)

n=[]
(n[:])
[123, 234]

n[0:2] means that it starts from index 0 and ends at index 2, but does not include index 2, that is, index 0, 1, which is exactly 2 elements, if the first element is 0, it can be omitted

print(n[:2])

You can also start at index 1 and take two elements

n=[]
(n[:])
[234, 456]

The index of the last element is -1

It is very useful to manipulate slices, first create a sequence of 0-99:

L=(())
(L)
(L[:])

take the last 10

L=(())
(L[-:])
[90, 91, 92, 93, 94, 95, 96, 97, 98, 99]

All numbers, take one every 5, in [start: end: step]

L=(())
(L[::])
[0, 5, 10, 15, 20, 25, 30, 35, 40, 45]

copy a list

L[:]

Tuple is also a list, but tuple is immutable, so tuple can also be sliced, and the result is still tuple

print((1,2,3,4,5,6)[:3])
(1,2,3,4,5,6) is a tuple [:3] is a slice operation

Strings can also be regarded as a kind of list, each element is a string, so strings can also be sliced, and the result is still a string

([:])
([::])

iterate

If given a list or tuple, we can use a for loop to traverse, this traversal is called iteration.

Although the data type of list has subscripts, many other data types do not have subscripts. However, as long as it is an iterable object, it can be iterated with or without subscripts, such as dict.

blob.png

Because the dict is not in the order of the list, the order of the iterated results is likely to be different. By default, dict iterates over key, if you want to iterate over value, you can use

for value in d.values():, if you want to iterate key and value at the same time, you can use for k,v in d.items().

Strings can also be iterated over

blob.png


So for a for loop, as long as it acts on an iterable object, for can work normally.

How to determine if an object is iterable

collections module

Iterable type

blob.png

Implement the subscript loop on the list

The enumerate function can turn a list into index-element pairs so that both the index and the element itself can be iterated over in a for loop.

ivalue  ([]):
    (ivalue)

The above loop, referencing two variables at the same time, is very common in python, the following example

blob.png



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324751049&siteId=291194637