Python primer for lists and tuples
- 2020-04-02 14:18:32
- OfStack
The main difference between lists and tuples is that lists can be modified and tuples cannot. In general, the following tables can replace tuples in almost all cases
For example, using sequences can represent information about an individual (name, age) in a database
>>> edward=['Edward Gumby',42]
A sequence can also contain other sequences
>>> edward=['Edward Gumby',42]
>>> john=['John Smith',50]
>>> database=[edward,john]
>>> database
[['Edward Gumby', 42], ['John Smith', 50]]
General sequence operation
All sequence operations can perform certain operations. These operations include indexing, sharding, adding, multiplying, and checking whether an element is a member of a sequence
The index
All the elements in the sequence are numbered -- increments from 0. These elements can be accessed individually by number, as follows:
>>> greeting='hello'
>>> greeting[0]
'h'
>>> greeting[-1]
'o'
>>> 'hello'[1]
'e'
If a function call returns a sequence, you can directly index the returned result, for example:
>>> fourth=raw_input('Year:')[3]
Year:2005
>>> fourth
'5'
View Code
Operation results:
>>>
Year: 1974
Month(1-12): 8
Day(1-31): 16
August 16th, 1974
shard
Shard operation is used to access elements in a certain range. Shard is achieved by two indexes separated by colons:
>>> tag='<a herf="http://www.python.org">Python web site</a>'
>>> tag[9:30]
'http://www.python.org'
>>> tag[32:-4]
'Python web site'
The first index is the number of the first element of the part to be extracted, and the last index is the number of the first element of the remaining part after sharding
>>> numbers=[1,2,3,4,5,6,7,8,9,10]
>>> numbers[3:6]
[4, 5, 6]
>>> numbers[0:1]
[1]
1. Elegant shortcuts
The last three elements are accessed, of course, for display
>>> numbers[7:10]
[8, 9, 10]
>>> numbers[-3:-1]
[8, 9]
>>> numbers[-3:0]
[]
>>> numbers[-3:]
[8, 9, 10]
Only the last shard completes the task. This method also applies to elements at the beginning of the sequence:
>>> numbers[:3]
[1, 2, 3]
In fact, if you need to copy the entire sequence, you can leave both indexes blank:
>>> numbers[:]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
2. Bigger step size
Sharding also has a third parameter, the step size, which is usually set implicitly. In general, the step size is 1, not 0, but can be negative, that is, the element can be extracted from right to left
The test code
The sequence together
Sequence concatenation can be performed by using the plus sign:
>>> [1,2,3]+[4,5,6]
[1, 2, 3, 4, 5, 6]
>>> 'hello.'+'world!'
'hello.world!'
>>> [1,2,3]+'world!'
Traceback (most recent call last):
File "<pyshell#107>", line 1, in <module>
[1,2,3]+'world!'
TypeError: can only concatenate list (not "str") to list
The multiplication
Multiplying the number x by a sequence produces a new sequence in which the original sequence is repeated x times
>>> 'python'*5
'pythonpythonpythonpythonpython'
>>> [42]*10
[42, 42, 42, 42, 42, 42, 42, 42, 42, 42]
membership
To check whether a value is in the sequence, use the in operator, which returns a Boolean value
>>> permissions='rw'
>>> 'w'in permissions
True
>>> 'x'in permissions
False
Enter your name: mlh
True
>>> subject='$$$ Get rich now!!! $$$'
>>> '$$$'in subject
True
Length, minimum and maximum
The built-in functions len, min and Max return the number of elements contained in the sequence, while the min and Max functions return the largest and smallest elements in the sequence, respectively
>>> numbers=[100,34,678]
>>> len(numbers)
3
>>> max(numbers)
678
>>> min(numbers)
34
>>> max(2,3)
3
>>> min(9,3,2,5)
2
List the function
The list function creates a list based on a string
>>> list('hello')
['h', 'e', 'l', 'l', 'o']
Basic list operations:
1, change the list: element assignment
Use index tags to assign values to specific, location-specific elements:
>>> x=[1,1,1]
>>> x[1]=2
>>> x
[1, 2, 1]
2. Delete elements
Use the del statement to:
>>> names=['Alice','Beth','Ceil','Dee-Dee','Earl']
>>> del names[2]
>>> names
['Alice', 'Beth', 'Dee-Dee', 'Earl']
Note: Cecil is removed completely and the list length has changed from 5 to 4
3. Slice assignment
The View Code
Listing method:
A method is a function that is closely related to some object, which may be a list, number, string, or other type of object.
1, append
The append method is used to append a new object to the end of the list:
>>> lst=[1,2,3]
>>> lst.append(4)
>>> lst
[1, 2, 3, 4]
2, cout
The count method counts the number of times an element appears in a list:
>>> ['to','be','or','not','to','be'].count('to')
2
>>> x=[[1,2],1,1,[2,1,[1,2]]]
>>> x.count(1)
2
>>> x.count([1,2])
1
3, the extend
The extend method can append multiple values from another sequence once at the end of a list
>>> a=[1,2,3]
>>> b=[4,5,6]
>>> a.extend(b)
>>> a
[1, 2, 3, 4, 5, 6]
>>> # Differential join operation
>>> a=[1,2,3]
>>> b=[4,5,6]
>>> a+b
[1, 2, 3, 4, 5, 6]
>>> a
[1, 2, 3]
4, the index
The index method is used to find the index position of a match from the list:
>>> knights=['we','are','the','knigths','who','say','ni']
>>> knights.index('who')
4
>>> knights=['we','are','the','knigths','who','say','ni']
>>> knights.index('herring')
Traceback (most recent call last):
File "<pyshell#184>", line 1, in <module>
knights.index('herring')
ValueError: 'herring' is not in list
Failure to find an exception is thrown
5, the insert
The insert method is used to insert objects into a list:
>>> numbers=[1,2,3,5,6,7]
>>> numbers.insert(3,'four')
>>> numbers
[1, 2, 3, 'four', 5, 6, 7]
>>> #extend The same way, insert The operation of the method can also be achieved by shard assignment
>>> numbers=[1,2,3,5,6,7]
>>> numbers[3:3]=['four']
>>> numbers
[1, 2, 3, 'four', 5, 6, 7]
6, pop
The pop method removes an element from the list (the default is the last one) and returns the value of that element:
>>> x=[1,2,3]
>>> x.pop()
3
>>> x
[1, 2]
>>> x.pop(0)
1
>>> x
[2]
Note: the pop method is the only listing method that can modify a list and return an element value (except None)
7, remove
The remove method is used to remove the first match of a value in the list:
>>> x=['to','be','or','not','to','be']
>>> x.remove('be')
>>> x
['to', 'or', 'not', 'to', 'be']
>>> x.remove('bee')
Traceback (most recent call last):
File "<pyshell#19>", line 1, in <module>
x.remove('bee')
ValueError: list.remove(x): x not in list
8, reverse
The reverse method, which stores the elements of the list in reverse, also changes the list without returning a value
>>> x=[1,2,3]
>>> x.reverse()
>>> x
[3, 2, 1]
9 , sort
The sort method is used to sort a list in its original position, changing the original list so that the elements are fixed
>>> x=[4,6,2,1,7,9]
>>> x.sort()
>>> x
[1, 2, 4, 6, 7, 9]
tuples
Tuples, like lists, are sequences, except that tuples cannot be modified:
An ordered collection of arbitrary objects
Store by offset
Is an immutable sequence type
Fixed length, heterogeneous, arbitrarily nested
Object reference array
Using commas to separate values automatically creates a tuple:
>>> 1,2,3
(1, 2, 3)
>>> ()
()
>>> 42
42
>>> 42,
(42,)
>>> (42,)
(42,)
Tuples are also (most of the time) enclosed in parentheses, and empty tuples can be represented by two parentheses with no content:
The tuple function
The tuple function does essentially the same thing as the list function: take a sequence as an argument and convert it to a tuple.
>>> tuple([1,2,3])
(1, 2, 3)
>>> tuple('abc')
('a', 'b', 'c')
>>> tuple((1,2,3))
(1, 2, 3)
Conversion between list and tuple:
>>> T=('cc','aa','dd','bb')
>>> tmp=list(T)
>>> tmp
['cc', 'aa', 'dd', 'bb']
>>> T=tuple(tmp)
>>> T
('cc', 'aa', 'dd', 'bb')