当前位置:网站首页>1. Circular nesting and understanding of lists
1. Circular nesting and understanding of lists
2022-07-04 10:38:00 【She was your flaw】
1. The implementation principle of loop nesting : External circulation once , Complete internal circulation
for x in range(5):
for y in range(2, 5):
print(x, y)
x Value range :0,1,2,3,4
The first 1 Time x=0: Execute the corresponding for loop , y The value range is : 2,3,4
The first 1 Time y=2: print(x, y) -> print(0, 2)
The first 2 Time y=3: print(x, y) -> print(0, 3)
The first 3 Time y=4: print(x, y) -> print(0, 4)
End of internal circulation
The first 2 Time x=1: Execute the corresponding for loop , y The value range is : 2,3,4
The first 1 Time y=2: print(x, y) -> print(1, 2)
The first 2 Time y=3: print(x, y) -> print(1, 3)
The first 3 Time y=4: print(x, y) -> print(1, 4)
End of internal circulation
2. What is a list (list)
1) A list is a container data type ( Sequence ), take []z As a sign of the container , Multiple elements are separated by commas :[ Elements 1, Elements 2, Elements 3,...]
2) The list is variable ( Number of elements 、 Values and order are variable ) - increase 、 Delete 、 Change ; The list is ordered - Subscript operation is supported
3) List requirements for elements : No requirement ( No matter what type of data can be used as elements of the list )
'''
1) An empty list
list1 = []
list2 = [ ]
print(type(list1), type(list2)) # <class 'list'> <class 'list'>
print(bool(list1), bool(list2)) # False False
print(len(list1), len(list2)) # 0 0
2) The list can save multiple data at the same time
list3 = [89, 90, 76, 99, 58]
print(list3)
list4 = [' Tan ', 3, 100, True]
print(list4)
3. check - Get elements
There are three situations : Get a single element 、 section 、 Traverse ( One by one )
1) Get a single element
grammar : list [ Subscript ]
function : Get the element corresponding to the specified subscript in the list
explain :
list - Any expression that results in a list , such as : Save the variables of the list 、 Specific list values, etc
[] - Fixed writing
Subscript - A subscript is also called an index , Is the position information of elements in an ordered sequence .
python Each element in the ordered sequence in has two sets of subscript values , Namely : From front to back 0 The subscript value that starts to increment ; From back to front -1 Subscript value that begins to decrease
Be careful : Subscript cannot be out of bounds
list3 = [89, 90, 76, 99, 58]
list3[ Subscript ]
[89, 90, 76, 99, 58][ Subscript ]
names = [' Diana Spencer ', ' Childcare cord ', ' Primary school hate ', ' Obama ', ' Kalma ', ' Laches ']
print(names[0]) # Diana Spencer
print(names[-1]) # Laches
print(names[-2]) # Kalma
print(names[-5]) # Childcare cord
print(names[10]) # Report errors
2) Traverse
The way 1 - Get each element in the list directly
for Variable in list :
The loop body
The way 2 - First get the subscript value of each element , Then get the element by subscript
for Subscript in range(len( list )):
The loop body
for Subscript in range(-1, -len( list )-1, -1):
The loop body
range(len( list )) == range( The number of elements in the list )
The way 3 - At the same time, get the subscript corresponding to each element in the list
for Subscript , Elements in enumerate( list ):
The loop body
print('---------------- Gorgeous divider --------------')
for index in range(len(names)):
print(index, names[index])
print('---------------- Gorgeous divider --------------')
for index, item in enumerate(names):
print(index, item)
practice 1: Count the number of people who failed
scores = [89, 67, 56, 90, 98, 30, 78, 51, 99]
count = 0
for x in scores:
if x < 60:
count += 1
print(' The number of failures :', count)
practice 2: Count the number of integers in the list
list7 = [89, 9.9, 'abc', True, 'abc', '10', 81, 90, 23]
count = 0
for x in list7:
if type(x) == int:
count += 1
print(count)
practice 3: seek nums The sum of all even numbers in
nums = [89, 67, 56, 90, 98, 30, 78, 51, 99]
sum1 = 0
for x in nums:
if x % 2 == 0:
sum1 += x
print(' The sum of all even numbers :', sum1)
4. increase - Additive elements
- Add a single element
list .append( Elements ) - Add an element at the end of the list
list .insert( Subscript , Elements ) - Inserts the specified element before the element corresponding to the specified subscript
movies = [' Fifty six degrees grey ', ' Godzilla vs. King Kong ', ' Peach blossom Man vs chrysanthemum monster ']
print(movies) # [' Fifty six degrees grey ', ' Godzilla vs. King Kong ', ' Peach blossom Man vs chrysanthemum monster ']
movies.append(' Shawshank's salvation ')
print(movies) # [' Fifty six degrees grey ', ' Godzilla vs. King Kong ', ' Peach blossom Man vs chrysanthemum monster ', ' Shawshank's salvation ']
movies.insert(2, ' Silent lamb ')
print(movies) # [' Fifty six degrees grey ', ' Godzilla vs. King Kong ', ' Silent lamb ', ' Peach blossom Man vs chrysanthemum monster ', ' Shawshank's salvation ']
2) Batch addition
list 1.extend( list 2) - Will list 2 All elements are added to the list 1 Behind
movies.extend([' Let the bullets fly ', ' Touch and ', 'V For vendetta '])
print(movies) # [' Fifty six degrees grey ', ' Godzilla vs. King Kong ', ' Silent lamb ', ' Peach blossom Man vs chrysanthemum monster ', ' Shawshank's salvation ', ' Let the bullets fly ', ' Touch and ', 'V For vendetta ']
practice : take scores Extract all the passing scores in
scores = [89, 67, 56, 90, 98, 30, 78, 51, 99]
scores2 = []
for x in scores:
if x >= 60:
scores2.append(x)
print(scores2)
First week homework
One 、 choice question
In the following variable names illegal Yes. ?(C)
A. abc
B. Npc
C. 1name
D ab_cd
In the following options Do not belong to The key word is ?(B)
A. and
B. print
C. True
D. in
Which of the following options corresponds to the correct code writing ?(C)
A.
print('Python') print(' Novice Village ') # Incorrect indentationB.
print('Python') print(' Novice Village ') # useless , separateC.
print('Python') print(' Novice Village ')D.
print('Python'' Novice Village ') # String is useless , separateThe following options can print 50 Yes. ?(B)
A.
print('100 - 50') # 100-50B.
print(100 - 50)About Quotes , The correct choice used in the following options is ?(D)
A.
print('hello)B.
print("hello')C.
print(“hello”)D.
print("hello")
Two 、 Programming questions
Write code and print on the console
good good study, day day up!a = 'good good study,day day up!' print(a)Write code and print on the console 5 Time
you see see, one day day!a = 'you see see, one day day!' b = 5 while b > 0: print(a) b -= 1Write code, print numbers 11、12、13、… 21
for x in range (11, 22): print(x)Write code, print numbers 11,13,15,17,…99
for x in range (11, 100, 2): print(x)Write code, print numbers :10、9、8、7、6、5
for x in range(10, 4, -1): print(x)Write code calculation :1+2+3+4+…+20 And
sum1 = 0for x in range(1, 21): sum1 += xprint(sum1) # 210Write code calculation 100 The sum of all even numbers within
sum2 = 0for x in range(2, 100, 2): sum2 += x print(sum2) # 2450Write code statistics 100~200 The median is 3 The number of
a = 0for x in range(103, 201, 10): a += 1 print(a) # 10Write code calculation
2*3*4*5*...*9Resultb = 1 for x in range(2, 10): b *= x print(b) # 362880Enter a number , If the number entered is even, print
even numbersOtherwise printOdd numberc = int(input(' Please enter :')) if c % 2 == 0: print(' even numbers ') else: print(' Odd number ')Statistics 1000 Endogenic quilt 3 Divisible but not by 5 The number of integers .
d = 0 for x in range(0, 1000, 3): if x % 5 != 0: d += 1 print(d) # 267
边栏推荐
- Recursive method to achieve full permutation (C language)
- Basic data types of MySQL
- MFC document view framework (relationship between classes)
- How do microservices aggregate API documents? This wave of show~
- Learning XML DOM -- a typical model for parsing XML documents
- [Galaxy Kirin V10] [desktop and server] FRP intranet penetration
- Recursion and divide and conquer strategy
- If the uniapp is less than 1000, it will be displayed according to the original number. If the number exceeds 1000, it will be converted into 10w+ 1.3k+ display
- The bamboo shadow sweeps the steps, the dust does not move, and the moon passes through the marsh without trace -- in-depth understanding of the pointer
- Development guidance document of CMDB
猜你喜欢
![[Galaxy Kirin V10] [server] failed to start the network](/img/0f/6d2f321da85bd7437d2b86547bd8b4.jpg)
[Galaxy Kirin V10] [server] failed to start the network

C language structure to realize simple address book

Safety reinforcement learning based on linear function approximation safe RL with linear function approximation translation 1

PHP code audit 3 - system reload vulnerability

Introduction to tree and binary tree

Seven examples to understand the storage rules of shaped data on each bit

Number of relationship models
如果不知道這4種緩存模式,敢說懂緩存嗎?

Realsense of d435i, d435, d415, t265_ Matching and installation of viewer environment
![[Galaxy Kirin V10] [server] FTP introduction and common scenario construction](/img/ef/f0f722aaabdc2d98723cad63d520e0.jpg)
[Galaxy Kirin V10] [server] FTP introduction and common scenario construction
随机推荐
[Galaxy Kirin V10] [desktop] FTP common scene setup
DDL language of MySQL database: create, modify alter, delete drop of databases and tables
Summary of several job scheduling problems
/*Rewrite the program, find the value of the element, and return the iterator 9.13: pointing to the found element. Make sure that the program works correctly when the element you are looking for does
How to quickly parse XML documents through C (in fact, other languages also have corresponding interfaces or libraries to call)
PHP programming language (1) - operators
Dos:disk operating system, including core startup program and command program
/*Write a loop to output the elements of the list container in reverse order*/
[Galaxy Kirin V10] [desktop] login system flash back
shell awk
Pod management
按键精灵打怪学习-识别所在地图、跑图、进入帮派识别NPC
Doris / Clickhouse / Hudi, a phased summary in June
[Galaxy Kirin V10] [server] set time synchronization of intranet server
leetcode1229. Schedule the meeting
Rhcsa operation
Recursive method to achieve full permutation (C language)
Introduction to extensible system architecture
DML statement of MySQL Foundation
[Galaxy Kirin V10] [server] failed to start the network