Python basic data types 3 (sixth lecture)

Insert picture description here

Tuple

1. Introduction to Tuples (Master)

    Tuple is a sequence structure , but an immutable sequence , you can simply understood as the contents of an immutable list. Except for the difference that internal elements cannot be modified, tuples and lists have similar usage.

  • Tuples consume less memory than lists
  • Tuples are recommended when the elements do not need to change
  • Recommended use list when the element needs to change

2. Tuple creation (mastery)

    Creating a tuple, as long as a comma delimited different data element using parentheses enclosed can.

tu = (1, 2, 3, 4)

    In addition, we can also directly create tuples through tuple() .

print(tuple('1231224')) # ('1', '2', '3', '1', '2', '2', '4')

3. The same operation of tuples and lists (familiar)

  • Use square brackets and subscripts to access elements
tu = (1, 2, 3, 4)
print(tu[0]) # 1
  • Slice (form a new tuple object)
tu = (1, 2, 3, 4)
print(tu[0:3]) # (1, 2, 3)
  • tuple.count() / tuple.index()
tu = (1, 2, 3, 4, 4, 4, 4, 4, 4)
print(tu.count(4)) # 6;求这个元素出现的次数
print(tu.index(4)) # 3:求这个元素最小的索引位置
  • Python built-in functions: reversed(), sorted()
tu = (1, 2, 4, 5, 3, 6, 8, 7)
print(tuple(reversed(tu))) # (7, 8, 6, 3, 5, 4, 2, 1);反转
tu = (1, 2, 4, 5, 3, 6, 8, 7)
print(sorted(tu)) # [1, 2, 3, 4, 5, 6, 7, 8];排序
  • Addition and multiplication
tu = (1, 2, 3, 4)
tu_2 = (5, 6, 7)
print(tu + tu_2) # (1, 2, 3, 4, 5, 6, 7)

tu = (1, 2)
print(tu * 2) # (1, 2, 1, 2)

4. Operations not allowed in tuples (familiar)

  • Not allowed to modify , add elements. (Level 1)
  • Not allowed to delete an element (but you can delete the entire tuple)
        In fact, the tuple will not have any internal elements happen to modify the action of the method. For example, the tuple has no remove, append, pop, etc. methods

5. Conversion between tuples and lists (mastery)

  • list --> tuple ; tuple(iterable)
tu = (1, 2, 3)
print(list(tu)) # [1, 2, 3]
  • tuple --> list ; list(iterable)
li = [1, 2, 3]
print(tuple(li)) # (1, 2, 3)

Dictionary (dict)

1. The creation of the dictionary (master)

    Python dictionary data type is the hash hash algorithm, based key-value pairs: (key value) in the form of an address value is calculated based on the value of the key, with very fast and takes check insertion speed. It is a variable object , so support modify, insert, or delete operation.

2. Dictionary creation (master)

  • dict()
  • dict(**kwargs) key-value pairs
  • dict(mapping) mapping
# dict()
PersonalInformation = {
    
    'name':'Jeff', 'age':18}PersonalInformation = {
    
    'name':'Jeff', 'age':18, 'hobbit':['play game', 'study python']}

# dict(**kwargs)
dic = dict(name='jeff', age=18)

# dict(mapping)
dic = dict[('name', 'jeff'), ('age', 18)]

    note:

  • Create a dictionary; the elements are not limited; the value can be any type; the key value can only be an immutable data type
  • In Python3.6 beginning, when the object remains in the dictionary key inserted sequence , and which contains a number of elements is not limited to , the type of value may be any other type of data .
  • Dictionary key must be immutable objects , such as integer, string, and tuple bytes, but to make
    use of most or string. Lists, dictionaries, sets, etc. cannot be used as keys. At the same time, the key in the same dictionary must be unique (overwrite if repeated) , but the value is not necessary.

6. Dictionary creation (extended)

  • map(func,*iterables):
    Pass the elements in iterables one by one to func for processing
# 需求:list('1234') --> [1,2,3,4]
# map:映射;将li中的每一个元素都映射到int中,再返回
li = list('1234')
print(list(map(int, li))) # [1, 2, 3, 4]
  • zip(iter1 [,iter2 […]]):
    Pack the corresponding elements in iter1 iter2 into tuples, and then return a list of these tuples.

# li_k = ['name','age'] 与 li_v = ['amy' , 18] 怎么组合成 键值对 的字典?
# zip:打包;将可迭代对象一一对应,打包成元组,进行返回
li_k = ['name', 'age']
li_v = ['amy', 18]
# print(zip(li_k, li_v)) #<zip object at 0x000001F33BC5BB48> zip类型
print(dict(zip(li_k, li_v))) # {'name': 'amy', 'age': 18}

7. Access the dictionary (master)

    A dictionary is a collection type , not the type of sequence , so there is no index index concept, but do not slice argument. However, the list is similar to the dictionary using the appropriate key into the brackets obtain the corresponding value of the
mode values
    such as: dic [exit_key]

dit = {
    
    'name': 'Jeff', 'age': 18}
print(dit['name'])

    Thinking: What happens to the program when the key value does not exist?

dit = {
    
    'name': 'Jeff', 'age': 18}
print(dit['asdf']) # 当key值不存在则报错

8. The addition and modification of the dictionary (master)

  • Increase is the dictionary to insert a new key-value pair
dit = {
    
    'name':'Jeff'}
dit['age'] = [18]
print(dit) # {'name': 'Jeff', 'age': [18]}
  • Modification is to the original key to give new value . Since only a key corresponding to a value, so many times a key assignment, the value of the preceding value of the latter will cover off.
dit = {
    
    'name':'Jeff'}
dit['age'] = [18]
print(dit) # {'name': 'Jeff', 'age': [18]}
dit['age'] = [20]
print(dit) # {'name': 'Jeff', 'age': [20]}

9. A series of deletions (mastery)

  • Delete dictionary element: del dic[exit_key] or dic.pop(exit_key)
dit = {
    
    'name': 'Jeff', 'age': [20]}
del dit['name'] # 单独删除某个元素
  • Delete the entire dictionary: del dic
dit = {
    
    'name': 'Jeff', 'age': [20]}
del dit# 删除整个字典
  • Clear the entire dictionary: dic.clear()
dit = {
    
    'name': 'Jeff', 'age': [20]}
dit.clear()

10. Common dictionary operations (familiar)

  • D.get(k[,d]) --> Returns the value of the specified key, if the value is not in the dictionary, it returns the default value
dit = {
    
    'name': 'Jeff', 'age': [20]}
print(dit.get('name')) # 跟方括号直接获取的结果一样,但是获取不存在的值时,不会报错
  • D.items() --> return traversable (key, value) tuple pairs as a list
dit = {
    
    'name': 'Jeff', 'age': [20]}
print(dit.items())
  • D.keys() --> Return all keys of the dictionary as a list
dit = {
    
    'name': 'Jeff', 'age': [20]}
print(dit.keys())

  • D.values() --> Return all the values ​​of the dictionary as a list
dit = {
    
    'name': 'Jeff', 'age': [20]}
print(dit.values())

3. Homework

Homework one

lis_1 = ['name','author','introduce']
lis_2 = ['NORWEGIAN WOOD','haruki Murakami','balabalabalabalabala']
presents lis_1 and lis_2 as key-value pairs

lis_1 = ['name', 'author', 'introduce']
lis_2 = ['NORWEGIAN WOOD', 'haruki Murakami', 'balabalabalabalabala']
print(dict(zip(lis_1, lis_2)))

Homework two

Amy_info={'name':'amy','addr':'hunan','weight':90} Get the key and value of Amy_info

import random

num = input('生成多少个:')
num_1 = 1
if str.isdigit(num):
    if float(num) <= 1000:
        while num_1 <= int(num):
            a = random.randint(0, 1000)
            print(a)
            num_1 += 1
    else:
        print('请输入小于一千的数')
else:
    print('请输入全数字')

Homework three (extended)

Generate N random integers between 1 and 1000 (N <= 1000). N is input by the user. Only one of the repeated numbers is kept, and the rest of the same numbers are removed, and then these numbers are sorted from small to large. ( Note that you need to use random integers here, you can understand the specific methods of the random module; for loops, range() functions, etc. are used in combination as a preview)

import random

num = input('生成多少个:')
num_1 = 1
b = set()
if str.isdigit(num):
    if float(num) <= 1000:
        while num_1 <= int(num):
            a = random.randint(0, 1000)
            b.add(a)
            num_1 += 1
    else:
        print('请输入小于一千的数')
else:
    print('请输入全数字')
print(b)

Homework four

  • How bytes convert characters
s = '123'
print(s.encode())
  • How characters convert bytes
s = b'123'
print(s.decode())

Homework five

Summarize which data types are mutable and which are immutable.

  • Numeric type (immutable)
  • Boolean type (immutable)
  • String type (immutable)
  • bytes data type (immutable)
  • Tuple (immutable)
  • Collection (variable)
  • List (variable)
  • Dictionary (variable)

Guess you like

Origin blog.csdn.net/weixin_51158247/article/details/112683760