Tuples and dictionaries

Tuples and dictionaries

1. What is a tuple

Tuple is the container data type: take () as the flag of the container, and multiple elements in it are separated by commas: (element 1, element 2, element 3...)

Tuples are immutable (can only be queried): tuples are ordered - subscript operation is supported
Element: like the list, there is no requirement

t1 =()
print(type(t1),len(t1))

Tuples with only one element must be followed by commas

list1 = [12]
print(list1,type(list1),len(list1))
t2 =(12,)
print(t2,type(t2))

1) General situation

2) In the absence of ambiguity, the parentheses of tuples can be omitted (directly separating multiple data with commas is also a tuple)

2. Query - get elements

1) The way to get elements from a list is supported by tuples

2) Get element 1 of tuple through variable - keep the number of variables consistent with the number of elements in tuple

point =(10,23,12)
x,y,z=point
print(x,y,z)
  1. Get element 2 of tuple through variable - if the number of variables is less than the number of elements, you must add * before one of them.

When obtaining, first let no variables obtain elements according to the positional relationship, and all the remaining variables to be brought (in the form of list)

info = ('Zhang San',18,175.187,90,67,89)
name,age,*other = info
print(name,age,other)

3. Tuples are immutable lists - immutable related operation tuples in the list are supported

3. Dictionary:

Define a variable to save a student's information: save multiple data with different meanings at the same time

stu = {
       'name':'millet',
       'age':20,
       'gender':'male',
       'weight':60,
       'math':89,
       'yuwen':70,
       'english':55
    }

print(stu['name'])
1. What is a dictionary (dict)

Data type of dictionary container: take {} as the container flag, and multiple key value pairs are separated by commas: {key 1: value 1, key 2: value 2, key 3: value 3.}
The dictionary is variable (adding, deleting and modifying are supported): the dictionary is out of order (subscript operation is not supported)

Requirements for elements:

Dictionary elements are key value pairs - keys must be immutable data (columns such as numbers, strings, tuples); Key is a unique value - no requirement

1) Empty dictionary: {}
d1={}
print(type(d1),len(d1),bool(d1)) #<class 'dict'> 0 False
2) Keys are immutable data
d2 = {1:10,'a':20,(10,20):30}
print(d2)
3) The key is unique
4) Dictionaries are out of order

2. Addition, deletion, modification and search of dictionary

1) Look up -- get the value of the dictionary
a. Get a single value

DICTIONARY [key] - get the value corresponding to the specified key in the dictionary. If the key does not exist

dog = {'name':'Caicai','age':3,'breed':'Earth dog','gender':'Bitch'}
print(dog['name'])
print(dog['gender'])
print(dog.get('name'))

Traversal; When traversing the dictionary through the for loop, the loop variable gets the keys of the dictionary in turn

for key in Dictionary:
loop

for key in dog:
    print(key,dog[key])

3. Dictionaries and lists in practical application define one class and save one class information

Structure I:

[expression for variable in sequence]

Structure II:

[number of expression for variable in conditions]

list1 = [10 for in range(4)]
print(list1)

list2 = [x for  in range(4)]
print(list2)

list3 = [x * 2 +1 for  x in  range(4)]
print(list3)

scores = [89,67,34,57,98]
list5 = [x>=60 for x in scores]
print(list5)

2. Application of derivation

Application 1:

Let all elements in the sequence be transformed uniformly

[expression for variable in sequence]

Application 2:

Transform the elements in the sequence that meet a certain condition (make two different transformations according to whether a certain condition is met)
Expression 1 if conditional statement else expression 2

Application 3:

# [89,67,34,56,10,90]->[0,89],[1,67],...]

nums = [89,67,34,56,10,90]
new_nums = [[x,nums[x]]] for x in range(len(nums))
print(new_nums)

Binocular operator:

Monocular operator; not

ternary operator

1. Ternary operator of C / Java

Conditional statements? Expression 1: expression 2 - if the conditional statement holds, the whole operation result is the value of expression 1, otherwise the whole operation result is the value of expression 2

Ternary operator of python
Expression 1 if conditional statement else expression 2 - if the conditional statement holds, the entire operation result is the value of expression 1, otherwise the entire operation result is the value of expression 2

age = 18
a = 'adult'if age >= 18 else 'under age':
print(a)

Exercise: divide all even numbers in nums by 2

[89, 67, 34, 56, 10, 90, 35] -> [89, 67, 17, 28, 5, 45, 35]

nums = [89, 67, 34, 56, 10, 90, 35]
new_nums =[89, 67, 34, 56, 10, 90, 35]
new_nums = [x if X  % 2  else x//2 for x in nums]
print(new_nums)

Delete all even numbers (extract all odd numbers)

nums = [89, 67, 34, 56, 10, 90, 35]
new_nums = [x for x in nums if x % 2]
print(new_nums)

1. Given a list of numbers, find the central element of the list.

nums = [23,45,89,20,19,40,30,8,9]
count = len(nums)
if count % 2:
    print(nums[count//2])
else:
    index = count //2
    print(nums[index//-1],nums[index//2])

2. Given a list of numbers, find the sum of all elements

nums = [23,45,89,20,19,40,30,8,9]
sum1=0
for item in nums:
    sum1 += item
print(sum1)

5.1. max.min - maximum, minimum

max (sequence)

nums = [34,89,78,56,90,23]
print(max(nums),min(nums))
sum  -  Finding the sum of elements in a number sequence
 sum (sequence)
print(sum(nums))

3.sorted - sort: generate a new list without modifying the order of elements in the original sequence: (for retaining the original data)

sorted (sequence); sorted (sequence, reverse=True)

nums = [34,89,78,56,90,23]
new_nums = sorted(nums)
print(nums) #[34, 89, 78, 56, 90, 23]
print(new_nums)#[23, 34, 56, 78, 89, 90]


nums = [34,89,78,56,90,23]
result = nums.sort()
print(nums)  #23, 34, 56, 78, 89, 90]
print(result)#None

4.len - get the number of elements in the sequence

Len (sequence)

5.list - list type conversion

List - all sequences can be converted into lists; When converting, directly convert the elements in the sequence into the elements of the list

print(list('abc'))
print(list(range(3)))

print(list(enumerate(nums)))

Job:

1. Create a list with 10 Shu Zongs in the list, ensure the order of elements in the list, arrange the weight of the list, and sort the use of the list in descending order

For example: randomly generated[70, 88, 91, 70, 107, 234, 91, 177, 282, 197]
		--- After weight removal [70, 88, 91, 107, 234, 177, 282, 197]
  	---- Descending sort [282, 234, 197, 177, 107, 91, 88, 70]
list1 = [70, 88, 91, 70, 107, 234, 91, 177, 282, 197]
list2 = []
for x in list1:
    if x not in list2:
        list2.append(x)
print('After weight removal:', list2)
print('In descending order:', sorted(list2, reverse=True))

2. Use the list derivation to complete the following requirements

a. Generate a data list with 3 digits in 1-100

The result is [3, 13, 23, 33, 43, 53, 63, 73, 83, 93]
print([x for x in range(101) if x % 10 == 3])

b. The use of list push is to extract the integers in the list

For example:[True, 17, "hello", "bye", 98, 34, 21] --- [17, 98, 34, 21]
print([x for x in lists if type(x) == int])

c. Use the list derivation to store the length of the string in the specified list

for example ["good", "nice", "see you", "bye"] --- [4, 4, 7, 3]
list4 = ["good", "nice", "see you", "bye"]
print([len(x) for x in list4])

4. A class dictionary has been as follows:

class1 = {
    'name': 'python2104',
    'address': '23 teach',
    'lecturer': {'name': 'Yu Ting', 'age': 18, 'QQ': '726550822'},
    'leader': {'name': 'Shu Ling', 'age': 18, 'QQ': '2343844', 'tel': '110'},
    'students': [
        {'name': 'stu1', 'school': 'Tsinghua University', 'tel': '1123', 'age': 18, 'score': 98, 'linkman': {'name': 'Zhang San', 'tel': '923'}},
        {'name': 'stu2', 'school': 'Panzhihua University', 'tel': '8999', 'age': 28, 'score': 76, 'linkman': {'name': 'Li Si', 'tel': '902'}},
        {'name': 'stu3', 'school': 'Chengdu University of Technology', 'tel': '678', 'age': 20, 'score': 53, 'linkman': {'name': 'Xiao Ming', 'tel': '1123'}},
        {'name': 'stu4', 'school': 'Sichuan University', 'tel': '9900', 'age': 30, 'score': 87, 'linkman': {'name': 'floret', 'tel': '782'}},
        {'name': 'stu5', 'school': 'Southwest Jiaotong University', 'tel': '665', 'age': 22, 'score': 71, 'linkman': {'name': 'Lao Wang', 'tel': '009'}},
        {'name': 'stu6', 'school': 'Chengdu University of Technology', 'tel': '892', 'age': 32, 'score': 80, 'linkman': {'name': 'Lao Wang 2', 'tel': '0091'}},
        {'name': 'stu7', 'school': 'Sichuan University', 'tel': '431', 'age': 17, 'score': 65, 'linkman': {'name': 'Lao Wang 3', 'tel': '0092'}},
        {'name': 'stu8', 'school': 'Panzhihua University', 'tel': '2333', 'age': 16, 'score': 32, 'linkman': {'name': 'Lao Wang 4', 'tel': '0093'}},
        {'name': 'stu9', 'school': 'Panzhihua University', 'tel': '565', 'age': 21, 'score': 71, 'linkman': {'name': 'Lao Wang 5', 'tel': '0094'}}
    ]
}

1 get class location

2) Get the name and phone number of the head teacher

3) Get the names and scores of all students

4) Get the names and phone numbers of all student contacts

5) Get the highest score in the class

6) Get the name of the student with the highest score in the class

7) Calculate the average score of students in the class

8) Count the number of minors in the class

9) Use a dictionary to count the number of people in each school, similar to: {'Tsinghua University': 1, 'Panzhihua College': 3}

Keywords: Python list

Added by Nabster on Sat, 15 Jan 2022 16:50:24 +0200