In general, the last of the finished chapters. The rest will be published a little less often, since they have not yet been written (but I’m sure they will, although it depends only on your wishes, dear readers :)
It should also be noted that this is, apparently, the last “simple lesson”, then I will try to go deeper into all aspects of programming that we went through “tops” and continue in more detail.
In general, those who are not interested - read the following news, and the rest - please go
.
')
Python for beginners. Chapter three "List, tuple, etc."Tuples.Tuples (eng. Tuple) is used to represent an immutable sequence of dissimilar objects. They are usually written in parentheses, but if ambiguity does not occur, then the brackets can be omitted.
>>> t = (2, 2.05, "Hello")
>>> t
(2, 2.0499999999999998, 'Hello')
>>> (a, b, c) = t
>>> print a, b, c
2 2.05 Hello
>>> z, y, x = t
>>> print z, y, x
2 2.05 Hello
>>> a = 1
>>> b = 2
>>> a, b = b, a
>>> print a, b
2 1
>>> x = 12,
>>> x
(12,)
As you can see from the example, the tuple can be used on the left side of the assignment operator. The values from the tuple on the left side of the assignment operator are associated with similar elements on the right side. This fact gives us such wonderful opportunities as mass initialization of variables and returning a set of values from a function at the same time. The last example demonstrates the creation of a single-element tuple (often referred to as a singleton).
ListsIn Python, there are no arrays in the traditional sense of the term. Instead, lists are used to store homogeneous (and not only) objects. They are defined in three ways.
Simple listing:
>>> a = [2, 2.25, "Python"]
>>> a
[2, 2.25, 'Python']
Convert string to list
>>> b = list ("help")
>>> b
['h', 'e', 'l', 'p']
Creation with the help of list inclusions. In this case, we take cubes of all odd numbers from 0 to 19.
I plan to devote a separate lesson to
this syntax. >>> c = [x ** 3 for x in range (20) if x% 2 == 1]
>>> c
[1, 27, 125, 343, 729, 1331, 2197, 3375, 4913, 6859]
A number of operators and functions are defined for working with lists:
len (s) the length of the sequence s
x in s Checking the ownership of the sequence element In newer versions of Python, you can check whether a substring belongs to a string. Returns True or False
x not in s = not x in s
s + s1 Concatenation of sequences
s * n or
n * s A sequence of n times repeated s. If n <0, an empty sequence is returned.
s [i] Returns the i-th element of s or len (s) + i-th if i <0
s [i: j: d] The cut from the sequence s from i to j with step d will be discussed below
min (s) Smallest element s
max (s) largest element s
s [i] = x the i-th element of the list s is replaced by x
s [i: j: d] = t The slice from i to j (with step d) is replaced by (list) t
del s [i: j: d] Remove the slice elements from the sequence
In addition, a number of methods are defined for lists.
append (x ) Adds an element to the end of a sequence.
count (x) Count the number of elements equal to x
extend (s) Adds the sequence s to the end of the sequence.
index (x) Returns the smallest i such that s [i] == x. Raises a ValueError exception if x is not found in s
insert (i, x) Inserts the element x into the i-th space
pop (i) Returns the i-th element, removing it from the sequence
reverse () Reverses the order of the s elements
sort ([cmpfunc]) Sorts the elements s. Can be specified its own comparison function cmpfunc
To convert a tuple to a list, there is a list function, for the inverse operation, a tuple.
The indexing of lists and the allocation of subsequences should once again be mentioned separately (this mechanism works similarly for strings). To obtain an element, brackets are used that contain the index of the element. Items are numbered from scratch. A negative index value points to items from the end. The first item at the end of the list (row) has index -1.
>>> s = [0, 1, 2, 3, 4]
>>> print s [0], s [-1], s [3]
0 4 3
>>> s [2] = -2
>>> print s
[0, 1, -2, 3, 4]
>>> del s [2]
>>> print s
[0, 1, 3, 4]
More difficult is the situation with the cuts. To obtain slices of the sequence in Python, it is customary to specify not the numbers of the elements, but the numbers of the “gaps” between them. Before the first element of the sequence, the gap has an index of 0, before the second - 1, and so on. Negative values count elements from the end of the line.
In general, the slice is written as follows:
list [start: end: step]
By default, the beginning of the slice is 0, the end of the slice is len (list), the step is 1. If no step is specified, the second “:” character can be omitted.
Using a slice, you can specify a subset to insert the list into another list, even if the length is zero. It is convenient to insert a list in a strictly defined position.
>>> l = range (12)
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
>>> l [1: 3]
[12]
>>> l [-1:]
[eleven]
>>> l [:: 2]
[0, 2, 4, 6, 8, 10]
>>> l [0: 1] = [- 1, -1, -1]
>>> l
[-1, -1, -1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
>>> del l [: 3]
>>> l
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
DictionariesDictionary (hash, predefined array) is a variable data structure for storing elements of the form key: value. Everything is easily shown by example.
Create hashes.
>>> h1 = {1: "one", 2: "two", 3: "three"}
>>> h2 = {0: "zero", 5: "five"}
>>> h3 = {"z": 1, "y": 2, "x": 3}
# Cycle for key-value pair
>>> for key, value in h1.items ():
... print key, "", value
...
1 one
2 two
3 three
# Cycle by keys
>>> for key in h2.keys ():
... print key, "", h2 [key]
...
0 zero
5 five
# Cycle by value
>>> for v in h3.values ():
... print v
...
2
3
one
# Add items from another hash
>>> h1.update (h3)
# Of pairs in hash
>>> len (h1)
6
Type fileObjects of this type are designed to work with external data. Most often, this object corresponds to a file on disk, but this is not always the case. File objects should support basic methods: read (), write (), readline (), readlines (), seek (), tell (), close (), etc.
The following example shows the file copy:
f1 = open ("file1.txt", "r")
f2 = open ("file2.txt", "w")
for line in f1.readlines ():
f2.write (line)
f2.close ()
f1.close ()
(this example can be written in a ton of other ways, many of which differ greatly in optimality, but this is also a topic for another conversation)In principle, it is absolutely indifferent to most functions whether an object of the file type or any other object with the same methods is passed to them. So, the above example can be very easily modified to download a file from the Internet, replacing the first line in it with the following code.
import urllib
f1 = urllib.urlopen ("http://python.onego.ru")
Tasks:- Develop a program for "mass upload" URLs from the file urls.txt
- Develop a program that downloads the page at the specified URL with all its contents.
- Write a program that, having received an arbitrary list as input, will remove all duplicate elements from it.