python loop keywords and lists

1, Nested loop comparison (code runtime management)

In python, if we want to pursue the simplicity of the code, we need to understand that more code will take more time to run, which will reduce the work efficiency. Next, we observe the effect through python's time library

import time
start=time.time()
for x in range(0, 35):
    # y stands for China Malaysia
    for y in range(0, 51):
        if 6 * x + 4 * y + (100 - x - y) == 200:
            print(f'Used in Malaysia{x}Horses,Used by China and Malaysia{y}Horses,Pony use{100 - x - y}Horses')
end =time.time()
print(end - start)


print('---------------------')
start=time.time()
for i in range(0, 35):
    for j in range(0, 51):
        for z in range(0, 101):
            if i + j + z == 100 and 6 * i + 4 * j + z == 200:
                print(f'Malaysia{i}Horse, middle horse{j}Horse, pony{z}Horses')
end = time.time()
print(end - start)

2, break and continue keywords

Case: number bomb game. Given a random number in a range, n people will guess, and there will be punishment if they guess correctly

import random

random: Random module
randint(a,b):from[a,b]Randomly select a number from
num = random.randint(1, 10)
# print(num)
flag = True
while flag:
    selfNum = int(input('Please enter the number you guessed:'))
    if selfNum > num:
        print('A little smaller')
    elif selfNum < num:
        print('A little bigger')
    else:
        print('right')
        flag = False

break and continue: loop keywords, which can only be used in loops
Break: when triggered, directly end the loop where the break is located
continue: when triggered, directly end the current cycle and enter the next cycle

for _ in range(2):
 for i in range(1, 12):
    if i % 5 == 0:  # 5 and 10 can be divided, so the following result will be output instead of its own value
        print('*******')
        # continue
        break  # End the current cycle directly
        print('====')
    else:
        print(i)

3, for else

Case: judge all prime numbers between 1 and 100
Prime number: the number with only 1 and its two factors is called prime number, and the minimum prime number is 2

for i in range(1, 101):
    if i == 1:
        print(f'{i}Not a prime number')
    elif i == 2:
        print(f'{i}Is a prime number')
    else:
        for j in range(2, i):
            if i % j == 0:
                print(f'{i}Not a prime number')
        else:
            print(f'{i}Is a prime number')

Application scenario: when all cases must be judged before conclusions can be reached, use the for else statement
Legal user name

Syntax: for variable in container: code block else: code block when the for loop ends normally, the else statement is executed. When the for loop ends abnormally, the else statement is not executed Keywords such as break and return will affect the normal end of the for loop

4, Nature of the list

1: Function: store multiple elements at once

2. Nature of the list

'''
1. The list is variable. (it can be modified, added, deleted and modified)
2. The list is ordered. (subscript, each element has its own fixed position)
3. Container mark of the list: []; Type of list: list
4. Any type of data can be stored in the list (it is suggested that the data types in a list should be consistent)
5. Duplicate elements are allowed in the list
'''

Create an empty list:

list2 = list()
print(list1, list2, list1 == list2)

Create a non empty list

list3 = [1, 1.1, True, None, 'abcde', [123], [1, 2, 3]]
print(list3)

len(): can view the number of elements in the container

print(len(list3))

Loop through the list

for i in list3:
    print(i, type(i))

Repetition and splicing of lists
Splicing

list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = [7, 8, 9]
print(list1+list2+list3)

repeat

print(list1*5)

5, The following table and slices

1. Subscript: position index of each element in the ordered container

Subscripts are divided into positive and negative subscripts
Forward subscript: starting from 0, increasing from left to right
Negative subscript: from - 1, decreasing from right to left
list1 = [10, 20, 30, 40]
Positive: 0, 1, 2, 3
Negative: - 4, - 3, - 2, - 1
Extract 20: print(list1[1]) print(list[-3])

2. Slice

Function: get some elements in an ordered container
Syntax: container [start:end:step] step is 1 by default and can not be written, indicating that the element is taken from left to right Start and end can also be used without writing. They represent the beginning and end. Start and end can use positive subscript and negative subscript Slices are left closed and right open intervals

list9 = [10, 20, 30,40, 50]
print(list9[1:-1])
print(list9[1:-1:2])
print(list9[:])
print(list9[:-1])
print(list9[1:])
print(list9[-1:-5:-1])
print(list9[::-1])
print(list9[-1:-5:-3])'''

If step > 0, the element corresponding to end must be behind the element corresponding to start The element to be acquired next time is the element with the subscript and step size of the element to be acquired this time. If step > 0, the element corresponding to end must be in front of the element corresponding to start. The element to be acquired next time is the element with the subscript and step size of the element to be acquired this time

practice:

list2 = ['Conan', 'Cardcaptor Sakura', 'Ultraman', 'Legend of Zhen Huan', 'One Piece', 'Naruto', 'Break through the sky']

1. Obtain ['Conan', 'Altman', 'one piece of sea', 'breaking the sky']
2. Obtain ['breaking the sky', 'Legend of Zhen Huan', 'Conan']
3. Obtain ['Altman', 'ever changing Sakura', 'Conan']
4. Obtain ['conan ']

print(list2[0::2])
print(list2[-1::-3])
print(list2[-5::-1])
print(list2[0::100])
print(list2[1])

Subscript cannot be out of bounds, slice can be out of bounds

list2 = ['Conan', 'changeable cherry', 'Altman', 'Legend of Zhen Huan', 'one piece of sea', 'Naruto', 'breaking the sky']

list2[8]
print(list2[0:100000])

6, Loop traversal

The loop traversal of ordered containers is divided into direct traversal and indirect traversal

Direct convenience

list1 = ['a', 'b', 'c', 'd']
for i in list1:
    print(i)

Indirect convenience

for index in range(len(list1)):
    print(f'subscript{index}--->element{list1[index]}')
for index in range(-len(list1), 0):
    print(f'subscript{index}--->element{list1[index]}')

9, Addition, deletion and modification of list

Add:

Append: append an element to the end of the list

insert: add an element anywhere in the list

extend: adds an element in a container to the list

list1 = []
print(list1)
list1.append('python')
list1.append('java')
print(list1)

list1.insert(1, 'c++')
print(list1)

list2 = ['ui', 'c', 'html', 'python']
list1.extend(list2)
print(list1)

Modification:

Modifying elements by subscript

list1[1]='python'
print(list1)

Delete:

del: delete the element through the subscript. If the subscript is out of range, an error will be reported

remove: deletes the specified element. The element to be deleted does not exist. An error is reported

Delete only one element at a time, from left to right

pop: delete the element through subscript. If the subscript is out of range, it will be wrong

Clear: clear the list

del list1[3]
print(list1)

list1.remove('c')
print(list1)

list1.remove('python')
print(list1)

list1.pop(0)
print(list1)

list1.clear()
print(list1)
print('                                 ')
Practice: 30 people on a boat, overloaded, 15 people need to get off the boat. So people form a line, and the position of the line is their number. Count off, start from 1, and get off the ship at 9. In this cycle, until there are only 15 people on the ship, ask which number of people got off the ship?
peopleList = []
for i in range(1, 31):
    peopleList.append(i)
print(peopleList)

while len(peopleList) > 15:
    num = 1
    while num < 9:
        num += 1
        peopleList.append(peopleList.pop(0))   #peopleList.pop(0) output 1

    people = peopleList.pop(0)
    print(people)

print(peopleList)

Tags: Python Algorithm numpy

Posted by paulsiew2 on Fri, 26 Aug 2022 00:29:49 +0300