Python learning notes - advanced features

  • section

Taking some elements of a list or tuple is a very common operation

>>> L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack']
['Michael', 'Sarah', 'Tracy']

L[0:3] indicates that it starts from index 0 to index 3, but does not include index 3. That is, the indexes 0, 1 and 2 are exactly three elements.

Do not write anything, just write [:] and you can copy a list as it is

>>> L[:]
[0, 1, 2, 3, ..., 99]

Tuple is also a list. The only difference is that tuple is immutable. Therefore, tuple can also be sliced, but the result of the operation is still tuple:

>>> (0, 1, 2, 3, 4, 5)[:3]
(0, 1, 2)

The string 'xxx' can also be regarded as a list

>>> 'ABCDEFG'[:3]
'ABC'
>>> 'ABCDEFG'[::2]
'ACEG'

? What do two ":" mean

[new features in python 2.3]

The python sequence slice address can be written as [start:end:step] and any one of start, stop or end can be deleted. a[::3] is every three elements of the sequence.

  • iteration

If a list or tuple is given, we can traverse the list or tuple through the for loop, which is called Iteration.

In Python, iteration is through for In, and in many languages, such as C language, iterative list is completed by subscript.

>>> d = {'a': 1, 'b': 2, 'c': 3}
>>> for key in d:
...     print(key)
...
a
c
b

By default, the key of dict iteration is. If you want to iterate over value, you can use for value in d.values(). If you want to iterate over key and value at the same time, you can use for k, v in d.items().

How to judge an object as an iteratable object?

The method is through collections Judgment of Iterable type of ABC module:

>>> from collections.abc import Iterable
>>> isinstance('abc', Iterable) # Is str iterative
True
>>> isinstance([1,2,3], Iterable) # Is the list iteratable
True
>>> isinstance(123, Iterable) # Is the integer iteratable
False

How to implement a subscript loop like Java for list?

Python's built-in enumerate function can turn a list into an index element pair, so that the index and the element itself can be iterated simultaneously in the for loop:

>>> for i, value in enumerate(['A', 'B', 'C']):
...     print(i, value)
...
0 A
1 B
2 C
  • List generation

List Comprehensions is a very simple but powerful built-in Python generator that can be used to create lists.

For example, to generate a list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], you can use list(range(1, 11))

The function range() allows Python to start counting from the first value you specify and stop after reaching the second value you specify, so the output does not contain the second value

range() Parameters

Python range()

range() takes mainly three arguments having the same use in both definitions:

  • start - integer starting from which the sequence of integers is to be returned
  • stop - integer before which the sequence of integers is to be returned.
    The range of integers ends at stop - 1.
  • step (Optional) - integer value which determines the increment between each integer in the sequence
  • range(2,11,2)
    The function range() starts with 2 and then continues to add 2 until it reaches or exceeds the final value (11)
>>> [x * x for x in range(1, 11) if x % 2 == 0]
[4, 16, 36, 64, 100]

Using list generation, you can write very concise code. For example, listing all files and directory names in the current directory can be realized by one line of code:

>>> import os # Import os module. The concept of module will be described later
>>> [d for d in os.listdir('.')] # os.listdir can list files and directories
['.emacs.d', '.ssh', '.Trash', 'Adlm', 'Applications', 'Desktop', 'Documents', 'Downloads', 'Library', 'Movies', 'Music', 'Pictures', 'Public', 'VirtualBox VMs', 'Workspace', 'XCode']

In fact, the for loop can use two or more variables at the same time. For example, dict's items() can iterate over key and value at the same time:

>>> d = {'x': 'A', 'y': 'B', 'z': 'C' }
>>> for k, v in d.items():
...     print(k, '=', v)
...
y = B
x = A
z = C

 

Keywords: Python Back-end

Added by AngelicS on Tue, 25 Jan 2022 20:08:37 +0200