Slicing operations for lists

Slicing operations for lists

How to create a list

  • Way to create a list: literal syntax
    list1 = ['apple', 'orange', 'pitaya', 'durian']
    print(list1)

  • The second way to create a list: constructor syntax
    list2 = list(range(1, 10))
    print(list2)

  • The third way to create a list: generative (deductive) syntax
    list3 = [i for i in range(1, 10)]
    print(list3)

Indexing and slicing

  • Positive index: 0 ~ N - 1 / negative index: - N ~ -1

print(list4[2:4])
print(list4[-3:-1])

  • Slice operation format:

nums[start​: end: ​step]

Start: the start position of the slice, including this position. For example: num [start:] get len (Num) from this location

end: the cut-off position of the slice, excluding this position.

Step: step size

"""
example01 - Slicing operations for lists

Author: Asus
Date: 2021/7/26
"""
import random

nums = [random.randrange(100) for _ in range(10)]

print(nums)
print(nums[2:])
print(nums[:])
print(nums[::-1])
print(nums[1:3])   # Left closed right open
print(nums[2:7:2])
print(nums[10:15]) # If the index is exceeded, no error will be reported

List related operations

# Repeat operation
list4 = [1, 10, 100] * 5
print(list4)

# Member operation -- > in / not in -- > true / false
print(10 in list4)
print(5 not in list4)

# merge
list5 = [1, 3, 5, 7]
list6 = [4, 4, 8]
list6.extend(list5)
# list6 += list5
print(list5)

# compare
list7 = [1, 3, 5, 7]
list8 = [1, 3, 4, 8, 9]
print(list5 == list7)
print(list7 != list8)
# Compare the size of the corresponding elements of the two lists,
print(list7 < list8)

Built in functions for lists

"""
example03 - List related operations

Author: Asus
Date: 2021/7/26
"""

ks = ['banana', 'grape', 'apple', 'waxberry', 'pitaya', 'apple']
if 'strawberry' in ks:
    print(ks.index('strawberry'))
if 'apple' in ks:
    print(ks.index('apple'))
if 'apple' in ks:
    print(ks.index('apple', 1))

append(): adds an element at the end of the list

insert(): inserts an element at the specified position in the list

ks = ['banana', 'grape', 'apple', 'waxberry', 'pitaya', 'apple']
# Add element
ks.append('blueberry')
ks.insert(1, 'watermelon')
print(ks)

pop(): the last element is deleted by default

remove(): deletes the specified element

ks = ['banana', 'grape', 'apple', 'waxberry', 'pitaya', 'apple']
# Delete element
ks.pop()
ks.pop(4)
# del ks[0]
while 'apple' in ks:
    ks.remove('apple')
print(ks)

Clear (): clear list elements

ks = ['banana', 'grape', 'apple', 'waxberry', 'pitaya', 'apple']
ks.clear()
print(ks)

Count the number of occurrences of elements in the list - > count()

ks = ['banana', 'grape', 'apple', 'waxberry', 'pitaya', 'apple']
print(ks.count('apple'))

Attach: displays all Chinese characters

"""
example04 - Display all Chinese characters
 Coding range of Chinese characters: 0 x4e00 ~ 0x9fa5

ord() ---> View the encoding corresponding to the character
chr() ---> The encoding is processed into corresponding characters
Author: Asus
Date: 2021/7/26
"""
# Display all Chinese characters
for i in range(0x4e00, 0x9fa6):
    print(chr(i), end=' ')

ord() - > view the encoding corresponding to the character
chr() - > process the encoding into corresponding characters

print(ord('b')) # View the position of letters
print(ord('z'))
print('banana' < 'zoo') # Compares the position of letters in an element

print(ord('Lee'))
print(ord('king'))
print('Li Si' < 'Wang Wu')

# Lists of different types cannot be compared in size unless the first element can get the result
items1 = ['apple', 'orange', 'pitaya', 'durian']
items2 = ['yes', 5, 6, 8, 9]
print(items1 < items2)

Sorting of lists

  • sort(): ascending by default. You can modify the reverse parameter to control ascending and descending
  • reverse(): reverses the elements of the list
"""
example05 - sort

Author: Asus
Date: 2021/7/26
"""

items = ['banana', 'grape', 'apple', 'waxberry', 'pitaya', 'apple']
# items = items[::-1] # Reverse
items.reverse() # Reverse
print(items)

# You can modify the reverse parameter to control ascending or descending order
items.sort(reverse=False)    # Default ascending order
print(items)

nums = ['1', '10', '234', '2', '35', '100']
nums.sort(key=int)	# Output as int
print(nums)

Select sort

  • Determine the minimum value min_value
  • Find out whether there is satisfaction ratio_ Value is smaller, if any, than min_value swap position
  • Repeat the above two steps until the list that meets the conditions is output
"""
example06 - Sort (premise: none) sort Function)

Author: Asus
Date: 2021/7/26
"""
# Simple selection sort
nums = [35, 12, 99, 58, 67, 42, 49, 31, 73]

for i in range(len(nums) - 1):
    # Suppose the first element is the minimum
    min_value, min_index = nums[i], i

    # Loop to find if there is a smaller value and note its location
    for j in range(i + 1, len(nums)):
        if nums[j] < min_value:
            min_value, min_index = nums[j], j

    # Change the minimum value to the front position
    nums[i], nums[min_index] = nums[min_index], nums[i]
print(nums)

Bubble sorting

Bubble sorting operates n-1 rounds of N data, and finds a maximum (small) value in each round.
The operation only compares and exchanges two adjacent numbers. Each round will exchange a maximum value to the beginning (end) of the data column, just like bubbling.

  1. Compare adjacent elements. If the first is bigger than the second, exchange them two;
  2. Do the same for each pair of adjacent elements, from the first pair at the beginning to the last pair at the end, so that the last element should be the largest number;
  3. Repeat the above steps for all elements except the last one;
  4. Repeat steps 1 to 3 until the sorting is completed.
#nums = [35, 12, 99, 58, 67, 42, 49, 31, 73]
nums = [9, 1, 2, 3, 4, 5, 6, 7, 8]

for i in range(1, len(nums)):
    swapped = False # Mark as no swap occurred
    for j in range(0, len(nums) - i):
        if nums[j] > nums[j + 1]:
            nums[j], nums[j + 1] = nums[j + 1], nums[j]
            swapped = True
    if not swapped:
        break

print(nums)

Random extraction and out of order

  • The sample function can sample list elements without putting them back
  • The choices function performs a put back sampling of list elements
  • The choice function can randomly select an element from the list
  • The shuffle function can disorder the list
"""
example08 - Random extraction and out of order

Author: Asus
Date: 2021/7/26
"""
import random
nums = ['Zhang San', 'Li Si', 'Wang Wu', 'offspring', 'Di Renjie', 'Li Yuanfang']

# The sample function can sample list elements without putting them back
print(random.sample(nums, 2))

# The choices function performs a put back sampling of list elements
print(random.choices(nums, k=5))

# The choice function can randomly select an element from the list
print(random.choice(nums))

# Out of order
random.shuffle(nums)
print(nums)

example

  1. Enter three integers and output them in descending order
"""
homework01 - 1. Enter three integers and output them in descending order

Author: Asus
Date: 2021/7/24
"""

nums = []
for _ in range(3):
    num = int(input('input data:'))
    nums.append(num)

    for i in range(1, len(nums)):
        for j in range(len(nums) - i):
            if nums[j] < nums[j + 1]:
                nums[j], nums[j + 1] = nums[j + 1], nums[j]
print(nums)
  1. Add 10 random integers to the list and find the second largest element

Additional: generative formula of list (derivation) - > concise and more efficient
nums = [random.randrange(1, 100) for _ in range(10)]

"""
homework02 - 2. Add 10 random integers to the list and find the second largest element

[a, b) --->random.random() * (b - a) + a

Author: Asus
Date: 2021/7/24
"""
import random
# nums = []
# for _ in range(10):
#     num = random.randrange(1, 100)     # Generate random decimal random random()
#     nums.append(num)

# Generating formula of list (derivation) - > the writing method is concise and more efficient
nums = [random.randrange(1, 100) for _ in range(10)]

# Derivation: generate odd numbers within 1 to 100
# nums = [i for i in range(1, 101, 2)]
print(nums)

f_max_value, s_max_value = nums[0], nums[1]     # Assume maximum and second largest values
if f_max_value < s_max_value:
    f_max_value, s_max_value = s_max_value, f_max_value
for i in range(2, len(nums)):
    if nums[i] > f_max_value:
        f_max_value, s_max_value = nums[i], f_max_value
    elif nums[i] == f_max_value:
        pass
    elif nums[i] > s_max_value:
        s_max_value = nums[i]
print(s_max_value)

​ 3. Lucky woman

"""
example09 - Lucky woman

15 men and 15 women went to sea by boat. The boat broke down and 15 of them needed to be thrown into the sea so that the others could survive;
All the people form a circle. Someone starts counting from 1. The person who reports to 9 is thrown into the sea, and the next person starts counting from 1 again,
Until 15 people were thrown into the sea. Finally, 15 women survived and 15 men were thrown into the sea.
Ask which positions were men and which positions were women.

Author: Asus
Date: 2021/7/26
"""

persons = [i for i in range(1, 31)]
for _ in range(15):
    persons = persons[9:] + persons[:8]
    print(persons)  # After the removed elements are output, the remaining elements
for i in range(1, 31):
    print('female' if i in persons else 'male', end=' ')

Compared with the above code, it is easier to understand, but the above code is more concise and readable

Each time it reaches 9, remove this position, and then count from 1 until 15 positions are removed.

persons = [True] * 30
index, counter, number = 0, 0, 0
while counter < 15:
    if persons[index]:
        number += 1
        if number == 9:
            persons[index] = False
            counter += 1
            number = 0
    index += 1
    if index == 30:
        index = 0
for person in persons:
    # Ternary conditional operation -- > if the expression after if is True, then take the value before if, otherwise take the value after else
    print('female' if person else 'male', end=' ')

4. Save 54 playing cards in a list, shuffle the cards, and distribute the cards to three players according to the licensing method of the landlords,
Give 3 more cards to the first player (landlord) and display the cards in each player's hand

First extract the following three elements, remove these three elements, and then assign values to each player using slices

"""
homework05 - Save 54 playing cards in a list, shuffle the cards, and distribute the cards to three players according to the licensing method of landlords,
             Give 3 more cards to the first player (landlord) and display the cards in each player's hand


Author: Asus
Date: 2021/7/26
"""
import random

nums = []

for i in range(1, 14):
    nums.append('block' + str(i))
    nums.append('Plum blossom' + str(i))
    nums.append('spade' + str(i))
    nums.append('Hearts' + str(i))
# print(nums)

fs = ['king', 'Xiao Wang']
pokers = nums + fs

random.shuffle(pokers)
print(len(pokers))
print(pokers)

player1 = []
player2 = []
player3 = []

nums = pokers[-1:-4:-1]
# print(nums)
for i in nums:
    if i in pokers:
        pokers.remove(i)

# print(pokers)

player1 = pokers[0:52:3]
player2 = pokers[1:52:3]
player3 = pokers[2:52:3]

player1 += nums

print(player1)
print(player2)
print(player3)

Another idea:

import random

suites = ['spade', 'Hearts', 'Plum blossom', 'block']
faces = ['A', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
# List generation formula (derivation)
cards = [f'{suite}{face}' for suite in suites for face in faces]
cards.append('Xiao Wang')
cards.append('king')

random.shuffle(cards)

# player1 = []
# player2 = []
# player3 = []
# Nested list 
# players = [[], [], []]
players = [[] for _ in range(3)]

for _ in range(17):
    for player in players:
        player.append(cards.pop())

players[0].extend(cards)    # The last three cards are given to the first player

for player in players:
    player.sort(key=lambda x: x[1:])
    for card in players:
        print(card, end=' ')
    print()

​ 5. Save the scores of 5 students and 3 courses

"""
example01 - Save the scores of 5 students and 3 courses

Author: Asus
Date: 2021/7/27
"""
import random
names = ['Li Bai', 'Zhuge Liang', 'Mozi', 'Sun WuKong', 'Zhao Yun']
courses = ['language', 'mathematics', 'English']
scores = [[random.randrange(50, 101) for _ in range(len(courses))] for _ in range(len(names)) ]

for i, name in enumerate(names):
    for j, course in enumerate(courses):
        print(f'{name}of{course}Achievement:{score[i][j]}')
# Count the average score of each student
for i, name in enumerate(names):
    print(f'{name}Average score of:{sum(score[i]) / 3:.lf}')
# Count the highest and lowest scores of each course
for j, course in enumerate(courses):
    temp = [scores[i][j] for i in range(len(names))]
    
    # temp = [scores[i][0] for i in range(len(names))]
	# temp = [scores[i][1] for i in range(len(names))]
	# temp = [scores[i][2] for i in range(len(names))]
    
    print(f'{course}Highest score:{max(temp)}')
    print(f'{course}Minimum score:{min(temp)}')

Keywords: Python

Added by saku on Wed, 12 Jan 2022 10:24:59 +0200