Python learning-Python container (list, tuples, Dictionary, set), python dictionary

Source: Internet
Author: User

Python learning-Python container (list, tuples, Dictionary, set), python dictionary

List:  
The list is ideal for locating an element by order and position, especially when the order or content of the element changes frequently. Unlike strings, the list is variable.
You can directly modify the original list: add new elements, delete or overwrite existing elements. In the list, elements with the same value can appear multiple times.
Use [] or list () to create a list. The list can contain zero or multiple elements separated by commas. The entire list is enclosed by square brackets:
>>> Empty_list = []
>>> Name = ['hangsan', 'lisi', 'hangzhou']
>>> Other_empty_list = list ()
>>> Other_empty_list []

List () converts other data types to a list:
1. Convert string to list
>>> List ('dog ')
['D', 'O', 'G']
2. Convert the ancestor to a list
>>> Tuple = ('dog ', 'cat', 'mouse ')
>>> List (tuple)
['Dog ', 'cat', 'mouse']
You can use split () to cut a string into a list composed of several substrings Based on the delimiter:
>>> Birthday = '2017/123'
>>> Birthday. split ('/')
['1', '6', '123']
If the string to be split contains consecutive delimiters, an empty string element will appear in the returned list:
>>> Splitme = 'A/B // c/d // e'
>>> Splitme. split ('/')
['A', 'B', '', 'C', 'D','', '']
Get and modify list elements:
>>> List = ['A', 'B', 'C', 'D', 'E', f']
>>> List [0]
'A'
>>> List [-1]
'F'
>>> List [2:]
['C', 'D', 'E', 'F']
>>> List [: 2]
['A', 'C', 'E']
>>> List [:-3]
['A', 'B', 'C']
>>> List [-3:]
['D', 'E', 'F']
>>> List [:-2]
['F', 'D', 'B']
# List containing list
>>> List1 = ['one', 'two', 'three ', 'four']
>>> List2 = ['cat', 'dog ', 'mouse']
>>> List3 = ['jack', 'Tom ', 'robet', 5]
>>> All_list = [list1, list2, 'hahaha', list3]
>>> All_list
[['One', 'two', 'three ', 'four'], ['cat', 'dog', 'mouse '], 'hahaha ', ['jack', 'Tom ', 'robet', 5]
>>> All_list [0]
['One', 'two', 'three ', 'four']
>>> All_list [0] [1]
'Two'
# List worthy of replacement
>>> List = ['A', 'C', 'B', 'D']
>>> List [1] = 'l'
>>> List
['A', 'l', 'B', 'D']

Common list operations: (all of the following operations are performed under the list by default)
List = ['one', 'two', 'three ', 'four']

1. append () add elements to the end
>>> List. append ('five ')
>>> List
['One', 'two', 'three ', 'four', 'five']

2. extend () or + = merge the list
>>> Other_list = ['Tom ', 'jack']
>>> List. extend (other_list)
>>> List
['One', 'two', 'three ', 'four', 'Tom ', 'jack']
Or:
>>> List + = other_list
>>> List
['One', 'two', 'three ', 'four', 'Tom ', 'jack']

3. insert () inserts an element at the specified position
>>> List. insert (3, 'hu ')
>>> List
['One', 'two', 'three ', 'hu', 'four']
>>> List. insert (10, 'hu ')
>>> List
['One', 'two', 'three ', 'four', 'hu']

4. del deletes the element at the specified position.
>>> Del list [1]
>>> List
['One', 'three ', 'four']
>>> Del list [-1]
>>> List
['One', 'two', 'three ']

5. remove () Delete the specified Element
>>> List. remove ('two ')
>>> List
['One', 'three ', 'four']

6. pop () obtains and deletes the elements at the specified position.
Pop () can also be used to obtain the element at the specified position in the list. However, after the element is obtained, it is automatically deleted. If you specify an offset for pop (), it returns the element at the corresponding offset position;
If this parameter is not specified,-1 is used by default. Therefore, pop (0) returns the Header element of the list, while pop () or pop (-1) returns the end element of the list:
>>> List. pop ()
'Four'
>>> List
['One', 'two', 'three ']

7. index () queries the position of elements with specific values
>>> List. index ('Three ')
2

8. in determines whether the value exists.
>>> 'Two' in list
True

9. count () records the number of occurrences of a specific value
>>> List. count ('one ')
1
>>> List. count ('five ')
0

10. Convert join () to a string
>>> ','. Join (list)
'One, two, three, four'
PS: Call sequence: join () is the inverse process of split ().
>>> C = 'AB, cd, ef'
>>> C. split (',')
['AB', 'cd', 'ef ']
>>> ','. Join (c)
'AB, cd, ef'

11. sort () rearrange Elements
The list method sort () sorts the original list and changes the content of the original list. The general function sorted () returns a copy of the sorted list, and the content of the original list remains unchanged.
If all the elements in the list are numbers, they are arranged in ascending order by default. If all elements are strings, they are sorted alphabetically:
>>> List. sort ()
>>> List
['Foue ', 'one', 'three', 'two']
Sometimes there are even multiple types-such as integer and floating point-as long as they can be automatically converted to each other:
>>> Numbers = [2, 1, 4.0, 3]
>>> Numbers. sort ()
>>> Numbers
[1, 2, 3, and 4.0]
By default, the sorting is in ascending order. You can change it to a descending order by adding the reverse = True parameter:
>>> Numbers = [2, 1, 4.0, 3]
>>> Numbers. sort (reverse = True)
>>> Numbers
[4.0, 3, 2, 1]
List_copy is a copy. Its creation does not change the content of the original list:
>>> List_copy = sorted (list)
>>> List_copy
['Foue ', 'one', 'three', 'two']

12. len () Get the list Length
>>> List. len ()
4

13. copy () function copy list
The list is called a. Then, use the copy () function to create B, use the list () function to create c, and use list parts to create d:
>>> A = [1, 2, 3]
>>> B = a. copy ()
>>> C = list ()
>>> D = a [:]
B, c, and d are all copies of a: they are new objects with their own values and are not associated with the List objects [1, 2, 3] pointed to by original. Changing a does not affect the replication of B, c, and d:
>>> A [0] = 'integer lists are boring'
>>>
['Integer lists are boring', 2, 3]
>>> B
[1, 2, 3]
>>> C
[1, 2, 3]
>>> D
[1, 2, 3]

Tuples:
Similar to the list, tuples are also a sequence composed of any type of elements. Unlike the list, tuples are immutable, which means that once the tuples are defined, you cannot add, delete, or modify elements.
Therefore, tuples are like a constant list. Use () to create a tuples
>>> Empty_tuple = ()
>>> Empty_tuply
()
When creating a tuples that contain one or more elements, each element must be followed by a comma, even if it contains only one element, it cannot be omitted:
>>> One_marx = 'groucho ',
>>> One_marx ('groucho ',)
PS: if the number of elements contained in the created tuples exceeds 1, the comma following the last element can be omitted.
A pair of parentheses is automatically added when the Python notebook interpreter outputs the tuples. You don't need to do this-defining tuples depends on the suffix comma of each element.
But if you are used to adding a pair of parentheses, it is understandable. You can enclose all elements in parentheses to make the program clearer:
You can assign values to multiple variables:
>>> Tuple = ('one', 'two', 'three ')
>>> A, B, c = tuple
>>>
'One'
>>> B
'Two'
>>> C
'Three'
This process is called the unpacking of tuples.

Tuples can exchange values of multiple variables without using the central values:
>>> Tuple1 = ('first ',)
>>> Tuple2 = ('last ',)
>>> Tuple1, tuple2 = tuple2, tuple1
>>> Tuple1
'Last'
>>> Tuple2
'First'

The tuple () function can use other types of data to create a metagroup:
>>> Marx_list = ['groucho ', 'chico', 'harpo']
>>> Tuple (marx_list)
('Groucho ', 'chico', 'harpo ')

Dictionary:
A dictionary is similar to a list, but the order of the elements is irrelevant because they are not accessed by an offset like 0 or 1. Instead, each element has a different key ),
You must use a key to access elements. A key is usually a string, but it can also be any other unchangeable types in Python: Boolean, integer, floating point, tuples, strings, and so on.
The dictionary is variable, so you can add, delete, or modify key-value pairs. Enclose a series of key-value pairs separated by commas (,) with braces {} to create a dictionary.
The simplest dictionary is an empty dictionary that does not contain any key-value pairs.
>>> Empty_dict = {}
>>> Empty_dict {}
Common dictionary operations:
Dict = {
'One': '1 ',
'Two': '2 ',
'Three ': '3 ',
}

1. Convert dict () to Dictionary
You can use dict () to convert a sequence containing a dual-value subsequence into a dictionary.
(You may often encounter this seed sequence, such as "strongren, 90, Carbon, 14" or "Vikings, 20, Packers, 7 .) The first element of each sub-sequence acts as the key, and the second element acts as the value.
>>> Lol = [['A', 'B'], ['C', 'D'], ['E', 'F']
>>> Dict (lol)
{'C': 'D', 'A': 'B', 'E': 'F '}
>>> Tos = ('AB', 'cd', 'ef ')
>>> Dict (tos)
{'C': 'D', 'A': 'B', 'E': 'F '}

2. [key] add or modify elements
>>> Dict ['one'] = 'A'
>>> Dict
{'One': 'A', 'two': '2', 'three ': '3 ',}
>>> Other = {'four': '4', 'five': '5 '}
>>> Dict. update (other)
>>> Dict
{'One': 'A', 'two': '2', 'three: '3', 'four ': '4', 'five ': '5 '}
PS: If the dictionary to be added contains the same key as the dictionary to be expanded, the new dictionary value will replace the original value:
>>> First = {'A': 1, 'B': 2}
>>> Second = {'B': 'platypus '}
>>> First. update (second)
>>> First
{'B': 'platypus', 'A': 1}

3. del deletes an element with the specified key.
>>> Del dict ['one']
>>> Dict
{'Two': '2', 'three ': '3 ',}

4. clear () delete all elements
>>> Dict. clear ()
>>> Dict {}

5. in determines whether a key exists (not a value)
>>> 'One' in dict
True
>>> '1' in dict
False

6. Use [key] to obtain elements
>>> Dict ['one']
'1'
PS: You can use the dictionary function get () to obtain elements.
>>> Dict. get ('one ')
'1'

7. keys () Get all keys
>>> Dict. keys ()
Dict_keys (['one', 'two', 'three '])
PS: in Python 2, keys () returns a list, and dict_keys () is returned in Python 3, which is the key iteration form.
You can only call list () to convert dict_keys to the list type.
>>> List (dict. keys ())
['One', 'two', 'three ']

8. Use values () to get all values
>>> List (dict. values ())
['1', '2', '3']

9. The items () method is used to obtain all key-value pairs. The items () method returns a list of traversal (Key, value) tuples.
>>> Dict. items ()
Dict_items ([('one', '1'), ('two', '2'), ('Three, '3')])
>>> List (dict. items ())
[('One', '1'), ('two', '2'), ('Three ', '3')]
Each key-value pair is returned in the form of tuples.

Set:
A set is like a dictionary with only keys left. Duplicate keys are not allowed. Like the dictionary key, the set is unordered.
Common Operations on a set:

1. Use set () to create a set
>>> Empty_set = set ()
>>> Empty_set ()

2. Use set () to convert other types to a set
You can use existing lists, strings, tuples, or dictionaries to create a set. duplicate values are discarded.
>>> Set ('Letters ') {'l', 'E', 't', 'R','s '}
Note that the preceding collection contains only one 'E' and one 'T', although the string 'Letters 'contains two.
>>> Set (['dasher', 'dancer ', 'prancer', 'mason-Dixon'])
{'Dancer ', 'dasher', 'prancer', 'mason-Dixon '}
>>> Set ('ummagumm', 'echoes', 'Atom Heart Mother '))
{'Ummagumm', 'Atom Heart Mother ', 'echoes '}
When the dictionary is passed into the set () function as a parameter, only keys are used:
>>> Set ({'apple': 'red', 'Orange ': 'Orange', 'cherry': 'red '})
{'Apple', 'cherry', 'Orange '}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.