Python contains six built-in sequences:List, tuples, strings, Unicode strings, buffer objects, xrange objects
This article mainly discusses the two most common types: List and tuples.
URL: http://www.cnblogs.com/archimedes/p/python-list-tuple.html.
The main difference between a list and a group is that a list can be modified, but a list cannot be modified. In general, the list can replace tuples in almost all cases.
For example, the sequence can represent the information of one person in the database (name, age)
>>> edward=['Edward Gumby',42]
The 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 operations
All sequential operations can perform certain specific operations. These operations include:Index, Shard, add, multiply, and check whether an element belongs to a Sequence member.
Index
All the elements in the sequence are numbered-starting from 0. These elements can be accessed by numbers separately, as shown below:
>>> greeting='hello'>>> greeting[0]'h'>>> greeting[-1]'o'>>> 'hello'[1]'e'
If a function call returns a sequence, you can index the returned result directly, for example:
>>> fourth=raw_input('Year:')[3]Year:2005>>> fourth'5'
# Print the date months = ['january ', 'february', 'march', '0000l', 'may', 'june' according to the given year, month, and day ', 'july', 'August ', 'September', 'October ', 'november', 'december'] #1 ~ Endings = ['st', 'nd', 'rd'] + 17 * ['th'] \ + ['st ', 'nd', 'rd'] + 7 * ['th'] \ + ['st'] year = raw_input ('year :') month = raw_input ('month (1-12): ') day = raw_input ('day (1-31):') month_number = int (Month) day_number = int (Day) # Remember to subtract 1 from the month and number of days to get the correct index month_name = months [month_number-1] ordinal = day + endings [day_number-1] print month_name + ''+ ordinal + ', '+ yearView Code
Running result:
>>> Year: 1974Month(1-12): 8Day(1-31): 16August 16th, 1974
Parts
You can use the sharding operation to access elements within a certain range. The sharding is implemented through 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 to be extracted, and the last index is the number of the first element in the remaining part After partitioning.
>>> numbers=[1,2,3,4,5,6,7,8,9,10]>>> numbers[3:6][4, 5, 6]>>> numbers[0:1][1]
1. Elegant shortcuts
Access the last three elements. Of course, you can perform the display operation.
>>> numbers[7:10][8, 9, 10]>>> numbers[-3:-1][8, 9]>>> numbers[-3:0][]>>> numbers[-3:][8, 9, 10]
Only the last part completes the task. This method also applies to the elements starting with 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. Larger step size
There is also a third parameter for fragment-step size, which is usually set implicitly. In general, the step size is 1 and cannot be 0, but can be negative, that is, extract elements from right to left.
>>> Numbers = [,] >>> numbers [] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> numbers [] [1, 3, 5, 7, 9] >>> numbers [] [4] >>> numbers [:: 4] [1, 5, 9] >>> numbers [8: 3:-1] [9, 8, 7, 6, 5] >>> numbers [10: 0:-2] [10, 8, 6, 4, 2] >>> numbers [0: 10:-2] [] >>> numbers [:: -2] [10, 8, 6, 4, 2] >>> numbers [5:-2] [6, 4, 2] >>> numbers [: 5: -2] [10, 8]Test code
Sequence Addition
You can use the plus sign to connect the sequence:
>>> [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
Multiplication
Multiply the number x by a sequence to generate a new sequence. In the new sequence, the original sequence will be repeated x times.
>>> 'python'*5'pythonpythonpythonpythonpython'>>> [42]*10[42, 42, 42, 42, 42, 42, 42, 42, 42, 42]
Member qualifications
To check whether a value is in a sequence, you can use the in operator, which returns a Boolean value.
>>> permissions='rw'>>> 'w'in permissionsTrue>>> 'x'in permissionsFalseEnter your name: mlhTrue>>> subject='$$$ Get rich now!!! $$$'>>> '$$$'in subjectTrue
Length, minimum, and maximum
Built-in functions len, min, max, and len return the number of elements in the sequence. min and max 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 Function
The list function can create a list based on strings.
>>> list('hello')['h', 'e', 'l', 'l', 'o']
Basic list operations:
1. Change the list: Element assignment
Index tags are used to assign values to specific and location-specific elements:
>>> x=[1,1,1]>>> x[1]=2>>> x[1, 2, 1]
2. Delete Elements
Use the del statement:
>>> names=['Alice','Beth','Ceil','Dee-Dee','Earl']>>> del names[2]>>> names['Alice', 'Beth', 'Dee-Dee', 'Earl']
Note: Cecil is completely deleted, and the list length also changes from 5 to 4.
3. multipart assignment
>>> Names ['P', 'E', 'R', 'L'] >>> names [2:] ['R ', 'L'] >>>> name = list ('perl ') >>> name ['P', 'E', 'R ', 'L'] >>>> name [2:] = list ('ar ') >>> name ['P', 'E', 'A ', 'R'] >>> name [1:] = list ('ython ') >>> name ['P', 'y', 't', 'h ', 'o', 'n'] >>> numbers = [] >>>> numbers [] = [2, 3, 4] >>> numbers [1, 2, 3, 4, 5] >>> numbers [] = [] >>> numbers [1, 5]View Code
List Method:
A method is a function closely related to some objects. objects may be lists, numbers, strings, or other types of objects. method call method: object. Method (parameter)
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 is used to count the number of times an element appears in the 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. extend
The extend method can append multiple values in another sequence at a time at the end of the list.
>>> A = [, 3] >>> B = [, 6] >>>. extend (B) >>> a [1, 2, 3, 4, 5, 6] >>## differentiate connection operations >>>> a = [1, 2, 3] >>> B = [, 6] >>> a + B [1, 2, 3, 4, 5, 6] >>> a [1, 2, 3]
4. index
The index method is used to locate the index location of a matching item 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
If it is not found, an exception is thrown.
5. insert
The insert method is used to insert objects to the list:
>>> Numbers = [1, 2, 3, 5, 6, 7] >>> numbers. insert (3, 'four ') >>> numbers [1, 2, 3, 'four', 5, 6, 7] >>># the same method as extend, the insert method operation can also be implemented using multipart 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 last one by default) and returns the value of this element:
>>> x=[1,2,3]>>> x.pop()3>>> x[1, 2]>>> x.pop(0)1>>> x[2]
Note: The pop method is the only list method that can modify the list and return element values (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 reversely stores the elements in the list. This method also changes the list but does not return values.
>>> x=[1,2,3]>>> x.reverse()>>> x[3, 2, 1]
9. sort
The sort method is used to sort the list in the original position and change the original list so that the elements in the list are sorted according to a certain number
>>> x=[4,6,2,1,7,9]>>> x.sort()>>> x[1, 2, 4, 6, 7, 9]
Tuples
Like lists, tuples are also a sequence. The only difference is that tuples cannot be modified:
- Ordered Set of any object
- Offset storage
- It belongs to an unchangeable sequence type
- Fixed Length, heterogeneous, arbitrary nesting
- Object reference array
If some values are separated by commas, A tuples are automatically created:
>>> 1,2,3(1, 2, 3)>>> ()()>>> 4242>>> 42,(42,)>>> (42,)(42,)
Tuples are also enclosed by parentheses (most of the time). Empty tuples can be expressed by two parentheses that do not contain content:
Tuple Function
The functions of the tuple function are basically the same as those of the list function: Use a sequence as a parameter and convert it to a tuples.
>>> tuple([1,2,3])(1, 2, 3)>>> tuple('abc')('a', 'b', 'c')>>> tuple((1,2,3))(1, 2, 3)
Conversion between lists and tuples:
>>> T=('cc','aa','dd','bb')>>> tmp=list(T)>>> tmp['cc', 'aa', 'dd', 'bb']>>> T=tuple(tmp)>>> T('cc', 'aa', 'dd', 'bb')