Learning python III: lists, tuples, dictionaries, collections

Lists, tuples, dictionaries, collections

List

Use nested lists to create another list that is in the list, such as:

>>>a = ['a', 'b', 'c']
>>> n = [1, 2, 3]
>>> x = [a, n]
>>> x
[['a', 'b', 'c'], [1, 2, 3]]
>>> x[0]
['a', 'b', 'c']
>>> x[0][1]
'b'
复制代码

related functions:

function description
list(seq) Convert a list of tuples
len(list) The number of list elements
list.append(obj) Add new object at the end of the list
list.count(obj) The number of times an element statistics appear in the list
list.extend(seq) A plurality of values ​​in another sequence added at the end of the list of one-time (with a new list of the original extended list)
list.pop([index=-1]) Removing one element in the list (default to the last element), and returns the value of the element
list.remove(obj) Remove the list a value of the first match
list.reverse() Reverse elements in the list
list.sort( key=None, reverse=False) The original list is sorted
list.clear() clear the list
list.copy() Copy List

Tuple

Elements of a tuple can not be changed. Tuples use parentheses, square brackets list .

>>>tup1 = ('Google', 'Runoob', 1997, 2000);
>>> tup2 = (1, 2, 3, 4, 5 );
>>> tup3 = "a", "b", "c", "d";   # 不需要括号也可以
>>> type(tup3)
<class 'tuple'>

tup1 = (); # 创建空元组
复制代码

When tuple contains only one element, the element needs to be added after the comma, or brackets will be used as the operator:

>>>tup1 = (50)
>>> type(tup1)     # 不加逗号,类型为整型
<class 'int'>
 
>>> tup1 = (50,)
>>> type(tup1)     # 加上逗号,类型为元组
<class 'tuple'>
复制代码

Element value tuples can not be deleted, but we can use the del statement to delete an entire tuple, the following examples:

#!/usr/bin/python3
 
tup = ('Google', 'Runoob', 1997, 2000)
 
print (tup)
del tup;
print ("删除后的元组 tup : ")
print (tup)

------------------------------------------

删除后的元组 tup : 
Traceback (most recent call last):
  File "test.py", line 8, in <module>
    print (tup)
NameError: name 'tup' is not defined
复制代码

tuple(seq)Convert list is a tuple. Distinguished list(seq)is to convert a tuple into a list. Following examples:

>>> list1= ['Google', 'Taobao', 'Runoob', 'Baidu']
>>> tuple1=tuple(list1)
>>> tuple1
('Google', 'Taobao', 'Runoob', 'Baidu')
复制代码

dictionary

Twice is not allowed the same key. When you create is assigned if the same key twice, the last value will be remembered, the following examples:

#!/usr/bin/python3
 
dict = {'Name': 'Runoob', 'Age': 7, 'Name': '小菜鸟'}
 
print ("dict['Name']: ", dict['Name'])

复制代码

Key must be immutable, it may be numbers, strings, or act as a tuple, and will not work with the list, the following examples:

#!/usr/bin/python3
 
dict = {['Name']: 'Runoob', 'Age': 7}
 
print ("dict['Name']: ", dict['Name'])

--------------------------------------

Traceback (most recent call last):
  File "test.py", line 3, in <module>
    dict = {['Name']: 'Runoob', 'Age': 7}
TypeError: unhashable type: 'list'
复制代码

str(dict) Output dictionary, printable string representation.

>>> dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
>>> str(dict)
"{'Name': 'Runoob', 'Class': 'First', 'Age': 7}"
复制代码
function description
radiansdict.fromkeys() Create a new dictionary, a sequence of elements do seq dictionary key, val is a dictionary of all the key corresponding to the initial value
radiansdict.values() Returns an iterator, you can use list () to convert to the list
pop(key[,default]) Remove dictionary given key corresponding to the key value, the return value is deleted. key value must be given. Otherwise, return default values.
popitem() Random return and remove the pair of keys and values ​​of the dictionary (the end of the general deletion).

set

A set of basic operations:

  1. Additive element
    added to the collection element x s, if existing elements, nothing is done.s.add( x )
>>>thisset = set(("Google", "Runoob", "Taobao"))
>>> thisset.add("Facebook")
>>> print(thisset)
{'Taobao', 'Facebook', 'Google', 'Runoob'}
复制代码

Another method, elements may be added, and the parameter may be a list of tuples, dictionaries, syntax is as follows: s.update( x )X may be a plurality, separated by commas.

>>>thisset = set(("Google", "Runoob", "Taobao"))
>>> thisset.update({1,3})
>>> print(thisset)
{1, 3, 'Google', 'Taobao', 'Runoob'}
>>> thisset.update([1,4],[5,6])  
>>> print(thisset)
{1, 3, 4, 5, 6, 'Google', 'Taobao', 'Runoob'}
复制代码
  1. The removable element is removed from the collection element x s, if the element does not exist, an error occurs. s.remove( x )
>>>thisset = set(("Google", "Runoob", "Taobao"))
>>> thisset.remove("Taobao")
>>> print(thisset)
{'Google', 'Runoob'}
>>> thisset.remove("Facebook")   # 不存在会发生错误
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'Facebook'
复制代码

In addition there is a method to remove elements in the collection, and if the element does not exist, an error does not occur. Format is as follows:s.discard( x )

>>>thisset = set(("Google", "Runoob", "Taobao"))
>>> thisset.discard("Facebook")  # 不存在不会发生错误
>>> print(thisset)
{'Taobao', 'Google', 'Runoob'}
复制代码

We can also set up a random element to delete the collection, syntax is as follows: s.pop()

thisset = set(("Google", "Runoob", "Taobao", "Facebook"))
x = thisset.pop()
print(x)
$ python3 test.py 
Runoob
复制代码

Repeating the test results are not the same. However, in the interactive mode, pop is the first element (the first element of the collection sorted) to delete the collection.

>>>thisset = set(("Google", "Runoob", "Taobao", "Facebook"))
>>> thisset.pop()
'Facebook'
>>> print(thisset)
{'Google', 'Taobao', 'Runoob'}
>>>
复制代码

Reproduced in: https: //juejin.im/post/5cf625a5f265da1bc14b156d

Guess you like

Origin blog.csdn.net/weixin_34101229/article/details/91467115