Python列表与字典练习题解决方案
在Python编程中,列表和字典是非常重要的数据结构。下面将介绍一系列关于列表和字典的练习题及其解决方案。
1. 列表练习题解决方案
1.1 按升序显示用户输入的整数列表
以下代码可以实现让用户输入整数,输入0时停止,然后将这些整数按升序显示:
# Start with an empty list
data = []
# Read values and add them to the list until the user enters 0
num = int(input("Enter an integer (0 to quit): "))
while num != 0:
data.append(num)
num = int(input("Enter an integer (0 to quit): "))
# Sort the values
data.sort()
# Display the values in ascending order
print("The values, sorted into ascending order, are:")
for num in data:
print(num)
在这个代码中,我们首先创建一个空列表
data
,然后通过
while
循环不断读取用户输入的整数,直到用户输入0为止。接着使用
sort()
方法对列表进行排序,最后遍历列表并打印每个元素。
1.2 移除数据集中的异常值
以下函数可以移除列表中的异常值:
def removeOutliers(data, num_outliers):
# Create a new copy of the list that is in sorted order
retval = sorted(data)
# Remove num outliers largest values
for i in range(num_outliers):
retval.pop()
# Remove num outliers smallest values
for i in range(num_outliers):
retval.pop(0)
# Return the result
return retval
# Read data from the user, and remove the two largest and two smallest values
def main():
# Read values from the user until a blank line is entered
values = []
s = input("Enter a value (blank line to quit): ")
while s != "":
num = float(s)
values.append(num)
s = input("Enter a value (blank line to quit): ")
# Display the result or an appropriate error message
if len(values) < 4:
print("You didn’t enter enough values.")
else:
print("With the outliers removed: ", removeOutliers(values, 2))
print("The original data: ", values)
# Call the main function
main()
该函数
removeOutliers
接受一个列表
data
和要移除的异常值数量
num_outliers
作为参数。首先创建一个排序后的列表副本
retval
,然后通过
pop()
方法移除最大和最小的异常值。在
main
函数中,我们读取用户输入的数据,检查数据数量是否足够,如果足够则调用
removeOutliers
函数移除异常值并显示结果。
1.3 避免重复单词
以下代码可以读取用户输入的单词,只显示每个单词一次,且按输入顺序显示:
# Read words from the user and store them in a list
words = []
word = input("Enter a word (blank line to quit): ")
while word != "":
# Only add the word to the list if
# it is not already present in it
if word not in words:
words.append(word)
# Read the next word from the user
word = input("Enter a word (blank line to quit): ")
# Display the unique words
for word in words:
print(word)
在这个代码中,我们创建一个空列表
words
,然后通过
while
循环不断读取用户输入的单词,只有当单词不在列表中时才将其添加到列表中,最后遍历列表并打印每个单词。
1.4 负数、零和正数的分类显示
以下代码可以读取用户输入的整数,分别显示负数、零和正数:
# Create three lists to store the negative, zero and positive values
negatives = []
zeros = []
positives = []
# Read all of the integers from the user, storing each integer in the correct list
line = input("Enter an integer (blank to quit): ")
while line != "":
num = int(line)
if num < 0:
negatives.append(num)
elif num > 0:
positives.append(num)
else:
zeros.append(num)
# Read the next line of input from the user
line = input("Enter an integer (blank to quit): ")
# Display all of the negative values, then all of the zeros, then all of the positive values
print("The numbers were: ")
for n in negatives:
print(n)
for n in zeros:
print(n)
for n in positives:
print(n)
我们创建了三个列表
negatives
、
zeros
和
positives
分别用于存储负数、零和正数。通过
while
循环读取用户输入的整数,并根据其正负性将其添加到相应的列表中,最后依次遍历这三个列表并打印其中的元素。
1.5 寻找完美数
一个数
n
如果其所有真因数之和等于
n
,则称其为完美数。以下代码可以找出1到10000之间的所有完美数:
from proper_divisors import properDivisors
LIMIT = 10000
def isPerfect(n):
# Get a list of the proper divisors of n
divisors = properDivisors(n)
# Compute the total of all of the divisors
total = 0
for d in divisors:
total = total + d
# Determine whether or not the number is perfect and return the appropriate result
if total == n:
return True
return False
# Display all of the perfect numbers between 1 and LIMIT
def main():
print("The perfect numbers between 1 and", LIMIT, "are:")
for i in range(1, LIMIT + 1):
if isPerfect(i):
print(" ", i)
# Call the main function
main()
在这个代码中,我们定义了
isPerfect
函数用于判断一个数是否为完美数。首先通过
properDivisors
函数获取该数的所有真因数,然后计算这些真因数的总和,最后判断总和是否等于该数。在
main
函数中,我们遍历1到10000之间的所有数,调用
isPerfect
函数判断是否为完美数,如果是则打印该数。
1.6 格式化列表显示
以下代码可以将列表中的元素用逗号分隔,并在最后两个元素之间添加“and”:
def formatList(items):
# Handle lists of 0 and 1 items as special cases
if len(items) == 0:
return "<empty>"
if len(items) == 1:
return str(items[0])
# Loop over all of the items in the list except the last two
result = ""
for i in range(0, len(items) - 2):
result = result + str(items[i]) + ", "
# Add the second last and last items to the result, separated by ‘‘and’’
result = result + str(items[len(items) - 2]) + " and "
result = result + str(items[len(items) - 1])
# Return the result
return result
# Read several items entered by the user and display them with nice formatting
def main():
# Read items from the user until a blank line is entered
items = []
line = input("Enter an item (blank to quit): ")
while line != "":
items.append(line)
line = input("Enter an item (blank to quit): ")
# Format and display the items
print("The items are %s." % formatList(items))
# Call the main function
main()
formatList
函数根据列表的长度进行不同的处理。如果列表为空,则返回
<empty>
;如果列表只有一个元素,则直接返回该元素的字符串表示。对于长度大于1的列表,我们通过循环将除最后两个元素外的元素用逗号连接起来,然后添加最后两个元素并在它们之间添加“and”。在
main
函数中,我们读取用户输入的元素,调用
formatList
函数进行格式化并显示结果。
1.7 生成随机彩票号码
以下代码可以生成6个1到49之间的不重复随机数作为彩票号码:
from random import randrange
MIN_NUM = 1
MAX_NUM = 49
NUM_NUMS = 6
# Use a list to store the numbers on the ticket
ticket_nums = []
# Generate NUM NUMS random but distinct numbers
for i in range(NUM_NUMS):
# Generate a number that isn’t already on the ticket
rand = randrange(MIN_NUM, MAX_NUM + 1)
while rand in ticket_nums:
rand = randrange(MIN_NUM, MAX_NUM + 1)
# Add the number to the ticket
ticket_nums.append(rand)
# Sort the numbers into ascending order and display them
ticket_nums.sort()
print("Your numbers are: ", end="")
for n in ticket_nums:
print(n, end=" ")
print()
我们使用
randrange
函数生成随机数,并通过
while
循环确保生成的随机数不重复。最后对生成的随机数列表进行排序并显示。
1.8 洗牌操作
以下代码可以创建一副标准的扑克牌并进行洗牌:
from random import randrange
# Construct a standard deck of cards with 4 suits and 13 values per suit
def createDeck():
# Create a list to hold the cards
cards = []
# For each suit and each value
for suit in ["s", "h", "d", "c"]:
for value in ["2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K", "A"]:
# Construct the card and add it to the list
cards.append(value + suit)
# Return the complete deck of cards
return cards
# Shuffle a deck of cards by modifying the deck passed to the function
def shuffle(cards):
# For each card
for i in range(0, len(cards)):
# Pick a random index between the current index and the end of the list
other_pos = randrange(i, len(cards))
# Swap the current card with the one at the random position
temp = cards[i]
cards[i] = cards[other_pos]
cards[other_pos] = temp
# Display a deck of cards before and after it has been shuffled
def main():
cards = createDeck()
print("The original deck of cards is: ")
print(cards)
print()
shuffle(cards)
print("The shuffled deck of cards is: ")
print(cards)
# Call the main function only if this file has not been imported into another program
if __name__ == "__main__":
main()
createDeck
函数用于创建一副标准的扑克牌,通过嵌套循环遍历4种花色和13种牌面,将它们组合成一张牌并添加到列表中。
shuffle
函数通过随机交换牌的位置来实现洗牌操作。在
main
函数中,我们创建一副牌,打印原始牌,调用
shuffle
函数进行洗牌,然后打印洗牌后的牌。
1.9 统计列表中指定范围内的元素数量
以下代码可以统计列表中大于等于最小值且小于最大值的元素数量:
def countRange(data, mn, mx):
# Count the number of elements within the acceptable range
count = 0
for e in data:
# Check each element
if mn <= e and e < mx:
count = count + 1
# Return the result
return count
# Demonstrate the countRange function
def main():
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Test a case where some elements are within the range
print("Counting the elements in [1..10] between 5 and 7...")
print("Result: %d Expected: 2" % countRange(data, 5, 7))
# Test a case where all elements are within the range
print("Counting the elements in [1..10] between -5 and 77...")
print("Result: %d Expected: 10" % countRange(data, -5, 77))
# Test a case where no elements are within the range
print("Counting the elements in [1..10] between 12 and 17...")
print("Result: %d Expected: 0" % countRange(data, 12, 17))
# Test a case where the list is empty
print("Counting the elements in [] between 0 and 100...")
print("Result: %d Expected: 0" % countRange([], 0, 100))
# Test a case with duplicate values
data = [1, 2, 3, 4, 1, 2, 3, 4]
print("Counting the elements in", data, "between 2 and 4...")
print("Result: %d Expected: 4" % countRange(data, 2, 4))
# Call the main program
main()
countRange
函数接受一个列表
data
、最小值
mn
和最大值
mx
作为参数,通过遍历列表中的每个元素,检查其是否在指定范围内,如果是则计数器加1。在
main
函数中,我们进行了多种测试用例,包括部分元素在范围内、所有元素在范围内、没有元素在范围内、列表为空和有重复值的情况。
1.10 字符串分词
以下代码可以将一个数学表达式字符串进行分词:
def tokenList(s):
# Remove all of the spaces from s
s = s.replace(" ", "")
# Loop through all of the characters in the string, identifying the tokens and adding them to
# the list
tokens = []
i = 0
while i < len(s):
# Handle the tokens that are always a single character: *, /, ˆ, ( and )
if s[i] == "*" or s[i] == "/" or s[i] == "ˆ" or s[i] == "(" or s[i] == ")" or s[i] == "+" or s[i] == "-":
tokens.append(s[i])
i = i + 1
# Handle a number without a leading + or -
elif s[i] >= "0" and s[i] <= "9":
num = ""
# Keep on adding characters to the token as long as they are digits
while i < len(s) and s[i] >= "0" and s[i] <= "9":
num = num + s[i]
i = i + 1
tokens.append(num)
# Any other character means the expression is not valid. Return an empty list to indicate
# that an error occurred.
else:
return []
return tokens
# Read an expression from the user, tokenize it, and display the result
def main():
exp = input("Enter a mathematical expression: ")
tokens = tokenList(exp)
print("The tokens are:", tokens)
# Call the main function only if this file has not been imported into another program
if __name__ == "__main__":
main()
tokenList
函数首先移除字符串中的所有空格,然后通过
while
循环遍历字符串中的每个字符。对于单个字符的运算符,直接将其添加到令牌列表中;对于数字,将连续的数字字符组合成一个数字令牌。如果遇到其他无效字符,则返回空列表表示表达式无效。在
main
函数中,我们读取用户输入的数学表达式,调用
tokenList
函数进行分词并显示结果。
1.11 区分一元和二元运算符
以下代码可以区分列表中一元和二元的
+
和
-
运算符:
from token_list import tokenList
def identifyUnary(tokens):
retval = []
# Process each token in the list
for i in range(len(tokens)):
# If the first token in the list is + or - then it is a unary operator
if i == 0 and (tokens[i] == "+" or tokens[i] == "-"):
retval.append("u" + tokens[i])
# If the token is a + or - and the previous token is an operator or an open parenthesis
# then it is a unary operator
elif i > 0 and (tokens[i] == "+" or tokens[i] == "-") and (tokens[i-1] == "+" or tokens[i-1] == "-" or tokens[i-1] == "*" or tokens[i-1] == "/" or tokens[i-1] == "("):
retval.append("u" + tokens[i])
# Any other token is not a unary operator so it is appended to the result without modification
else:
retval.append(tokens[i])
# Return the new list of tokens where the unary operators have been marked
return retval
# Demonstrate that unary operators are marked correctly
def main():
# Read an expression from the user, tokenize it, and display the result
exp = input("Enter a mathematical expression: ")
tokens = tokenList(exp)
print("The tokens are:", tokens)
# Identify the unary operators in the list of tokens
marked = identifyUnary(tokens)
print("With unary operators marked: ", marked)
# Call the main function only if this file has not been imported into another program
if __name__ == "__main__":
main()
identifyUnary
函数遍历令牌列表,根据特定条件判断一个
+
或
-
运算符是一元还是二元运算符。如果是一元运算符,则在其前面添加
u
进行标记。在
main
函数中,我们读取用户输入的数学表达式,先进行分词,然后调用
identifyUnary
函数标记一元运算符并显示结果。
1.12 生成列表的所有子列表
以下代码可以生成一个列表的所有子列表:
def allSublists(data):
# Start out with the empty list as the only sublist of data
sublists = [[]]
# Generate all of the sublists of data from length 1 to len(data)
for length in range(1, len(data) + 1):
# Generate the sublists starting at each index
for i in range(0, len(data) - length + 1):
# Add the current sublist to the list of sublists
sublists.append(data[i : i + length])
# Return the result
return sublists
# Demonstrate the allSublists function
def main():
print("The sublists of [] are: ")
print(allSublists([]))
print("The sublists of [1] are: ")
print(allSublists([1]))
print("The sublists of [1, 2] are: ")
print(allSublists([1, 2]))
print("The sublists of [1, 2, 3] are: ")
print(allSublists([1, 2, 3]))
print("The sublists of [1, 2, 3, 4] are: ")
print(allSublists([1, 2, 3, 4]))
# Call the main function
main()
allSublists
函数通过两层循环生成列表的所有子列表。外层循环控制子列表的长度,内层循环控制子列表的起始位置。在
main
函数中,我们对不同长度的列表调用
allSublists
函数并打印结果。
1.13 埃拉托斯特尼筛法求素数
以下代码可以使用埃拉托斯特尼筛法找出2到用户输入的限制范围内的所有素数:
# Read the limit from the user
limit = int(input("Identify all primes up to what limit? "))
# Create a list that contains all of the integers from 0 to limit
nums = []
for i in range(0, limit + 1):
nums.append(i)
# ‘‘Cross out’’ 1 by replacing it with a 0
nums[1] = 0
# ‘‘Cross out’’ all of the multiples of each prime number that we discover
p = 2
while p < limit:
# ‘‘Cross out’’ all multiples of p (but not p itself)
for i in range(p*2, limit + 1, p):
nums[i] = 0
# Find the next number that is not ‘‘crossed out’’
p = p + 1
while p < limit and nums[p] == 0:
p = p + 1
# Display the result
print("The primes up to", limit, "are:")
for i in nums:
if nums[i] != 0:
print(i)
在这个代码中,我们首先创建一个包含0到用户输入限制的整数列表
nums
,然后将1标记为非素数(用0表示)。接着从2开始,将每个素数的倍数标记为非素数。最后遍历列表,打印出所有未被标记为非素数的数,即素数。
2. 字典练习题解决方案
2.1 反向查找字典键
以下代码可以在字典中进行反向查找,找出所有映射到指定值的键:
def reverseLookup(data, value):
# Construct a list of the keys that map to value
keys = []
# Check each key and add it to keys if the values match
for key in data:
if data[key] == value:
keys.append(key)
# Return the list of keys
return keys
# Demonstrate the reverseLookup function
def main():
# A dictionary mapping 4 French words to their English equivalents
frEn = {"le": "the", "la": "the", "livre": "book", "pomme": "apple"}
# Demonstrate the reverseLookup function with 3 cases: One that returns multiple keys,
# one that returns one key, and one that returns no keys
print("The french words for ’the’ are: ", reverseLookup(frEn, "the"))
print("Expected: ['le', 'la']")
print()
print("The french word for ’apple’ is: ", reverseLookup(frEn, "apple"))
print("Expected: ['pomme']")
print()
print("The french word for ’asdf’ is: ", reverseLookup(frEn, "asdf"))
print("Expected: []")
# Call the main function only if this file has not been imported into another program
if __name__ == "__main__":
main()
reverseLookup
函数接受一个字典
data
和一个值
value
作为参数,通过遍历字典中的每个键,检查其对应的值是否等于
value
,如果相等则将该键添加到结果列表中。在
main
函数中,我们创建了一个法语到英语的映射字典,进行了三种不同情况的反向查找测试。
2.2 两个骰子模拟
以下代码可以模拟多次掷两个骰子,并将模拟结果与概率理论预期结果进行比较:
from random import randrange
NUM_RUNS = 1000
D_MAX = 6
# Simulate rolling two six-sided dice
def twoDice():
# Simulate two dice
d1 = randrange(1, D_MAX + 1)
d2 = randrange(1, D_MAX + 1)
# Return the total
return d1 + d2
# Simulate many rolls and display the result
def main():
# Create a dictionary of expected proportions
expected = {2: 1/36, 3: 2/36, 4: 3/36, 5: 4/36, 6: 5/36, 7: 6/36, 8: 5/36, 9: 4/36, 10: 3/36, 11: 2/36, 12: 1/36}
# Create a dictionary that maps from the total of two dice to the number of occurrences
counts = {2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0}
# Simulate NUM RUNS rolls, and count each roll
for i in range(NUM_RUNS):
t = twoDice()
counts[t] = counts[t] + 1
# Display the simulated proportions and the expected proportions
print("Total Simulated Expected")
print(" Percent Percent")
for i in sorted(counts.keys()):
print("%5d %11.2f %8.2f" % (i, counts[i] / NUM_RUNS * 100, expected[i] * 100))
# Call the main function
main()
在这个代码中,我们定义了
twoDice
函数用于模拟掷两个骰子并返回它们的总和。在
main
函数中,我们创建了两个字典,一个存储每个总和的预期概率,另一个存储每个总和的实际出现次数。然后进行1000次模拟掷骰子,更新实际出现次数。最后打印出模拟结果和预期结果的百分比。
2.3 计算字符串中唯一字符的数量
以下代码可以使用字典计算字符串中唯一字符的数量:
# Read the string from the user
s = input("Enter a string: ")
# Add each character to a dictionary with a value of True. Once we are done the number
# of keys in the dictionary will be the number of unique characters in the string.
characters = {}
for ch in s:
characters[ch] = True
# Display the result
print("That string contained", len(characters), "unique character(s).")
在这个代码中,我们遍历字符串中的每个字符,将其作为键添加到字典中,并将值设为
True
。由于字典的键是唯一的,最后字典的键数量就是字符串中唯一字符的数量。
2.4 判断两个字符串是否为变位词
以下代码可以判断两个字符串是否为变位词:
# Compute the frequency distribution for the characters in a string
def characterCounts(s):
# Create a new, empty dictionary
counts = {}
# Update the count for each character in the string
for ch in s:
if ch in counts:
counts[ch] = counts[ch] + 1
else:
counts[ch] = 1
# Return the result
return counts
# Determine if two strings entered by the user are anagrams
def main():
# Read the strings from the user
s1 = input("Enter the first string: ")
s2 = input("Enter the second string: ")
# Get the character counts for each string
counts1 = characterCounts(s1)
counts2 = characterCounts(s2)
# Display the result
if counts1 == counts2:
print("Those strings are anagrams.")
else:
print("Those strings are not anagrams.")
# Call the main function
main()
characterCounts
函数用于计算字符串中每个字符的出现频率,返回一个字典。在
main
函数中,我们读取两个字符串,分别计算它们的字符频率分布,然后比较这两个字典是否相等,如果相等则说明这两个字符串是变位词。
2.5 计算Scrabble™得分
以下代码可以使用字典计算一个单词的Scrabble™得分:
# Initialize the dictionary so that it maps from letters to points
points = {"A": 1, "B": 3, "C": 3, "D": 2, "E": 1, "F": 4, "G": 2, "H": 4, "I": 1, "J": 2, "K": 5, "L": 1, "M": 3, "N": 1, "O": 1, "P": 3, "Q": 10, "R": 1, "S": 1, "T": 1, "U": 1, "V": 4, "W": 4, "X": 8, "Y": 4, "Z": 10}
# Read a word from the user
word = input("Enter a word: ")
# Compute the score for the word
uppercase = word.upper()
score = 0
for ch in uppercase:
score = score + points[ch]
# Display the result
print(word, "is worth", score, "points.")
我们首先创建一个字典
points
,将每个字母映射到其对应的得分。然后读取用户输入的单词,将其转换为大写,遍历单词中的每个字母,根据字典计算得分。最后打印出单词和得分。
2.6 创建随机宾果卡
以下代码可以创建并显示一个随机的宾果卡:
from random import randrange
NUMS_PER_LETTER = 15
# Create a Bingo card with randomly generated numbers
def createCard():
card = {}
# The range of integers that can be generated for the current letter
lower = 1
upper = 1 + NUMS_PER_LETTER
# For each of the five letters
for letter in ["B", "I", "N", "G", "O"]:
# Start with an empty list for the letter
card[letter] = []
# Keep generating random numbers until we have 5 unique ones
while len(card[letter]) != 5:
next_num = randrange(lower, upper)
# Ensure that we do not include any duplicate numbers
if next_num not in card[letter]:
card[letter].append(next_num)
# Update the range of values that will be generated for the next letter
lower = lower + NUMS_PER_LETTER
upper = upper + NUMS_PER_LETTER
# Return the card
return card
# Display a Bingo card with nice formatting
def displayCard(card):
# Display the headings
print("B I N G O")
# Display the numbers on the card
for i in range(5):
for letter in ["B", "I", "N", "G", "O"]:
print("%2d " % card[letter][i], end="")
print()
# Create a random Bingo card and display it
def main():
card = createCard()
displayCard(card)
# Call the main function only if this file has not been imported into another program
if __name__ == "__main__":
main()
createCard
函数用于创建一个随机的宾果卡,通过循环为每个字母生成5个不重复的随机数。
displayCard
函数用于格式化显示宾果卡。在
main
函数中,我们调用
createCard
函数创建宾果卡,然后调用
displayCard
函数显示宾果卡。
通过以上这些练习题和解决方案,我们可以更深入地理解Python中列表和字典的使用,提高编程能力。希望这些内容对你有所帮助!
Python列表与字典练习题解决方案
3. 总结与对比
为了更清晰地理解列表和字典在不同场景下的应用,我们可以对上述练习题进行总结和对比。以下是一个对比表格:
| 类型 | 功能 | 关键代码元素 | 适用场景 |
| — | — | — | — |
| 列表 | 按升序显示用户输入的整数 |
data.sort()
| 需要对用户输入的整数进行排序显示时 |
| 列表 | 移除数据集中的异常值 |
retval.pop()
和
retval.pop(0)
| 处理数据时需要去除极端值的情况 |
| 列表 | 避免重复单词 |
if word not in words: words.append(word)
| 读取用户输入单词,需要去重显示的场景 |
| 列表 | 负数、零和正数的分类显示 | 三个列表
negatives
、
zeros
和
positives
分别存储不同类型的数 | 对用户输入的整数按正负性分类显示的场景 |
| 列表 | 寻找完美数 |
isPerfect
函数判断一个数是否为完美数 | 寻找特定范围内完美数的场景 |
| 列表 | 格式化列表显示 |
formatList
函数根据列表长度进行不同处理 | 需要将列表元素以特定格式显示的场景 |
| 列表 | 生成随机彩票号码 |
randrange
函数生成随机数并确保不重复 | 生成随机且不重复数字的场景 |
| 列表 | 洗牌操作 |
createDeck
函数创建扑克牌,
shuffle
函数交换牌的位置 | 模拟洗牌等随机排列的场景 |
| 列表 | 统计列表中指定范围内的元素数量 |
countRange
函数遍历列表检查元素是否在指定范围 | 统计列表中特定范围元素数量的场景 |
| 列表 | 字符串分词 |
tokenList
函数对数学表达式字符串进行分词 | 处理数学表达式字符串,需要进行分词的场景 |
| 列表 | 区分一元和二元运算符 |
identifyUnary
函数标记一元运算符 | 处理数学表达式,需要区分运算符类型的场景 |
| 列表 | 生成列表的所有子列表 |
allSublists
函数通过两层循环生成子列表 | 需要获取列表所有子列表的场景 |
| 列表 | 埃拉托斯特尼筛法求素数 | 标记非素数并打印素数 | 寻找特定范围内素数的场景 |
| 字典 | 反向查找字典键 |
reverseLookup
函数遍历字典查找键 | 在字典中根据值查找键的场景 |
| 字典 | 两个骰子模拟 |
twoDice
函数模拟掷骰子,两个字典存储预期和实际结果 | 模拟随机事件并对比预期和实际结果的场景 |
| 字典 | 计算字符串中唯一字符的数量 | 遍历字符串将字符作为键添加到字典 | 统计字符串中唯一字符数量的场景 |
| 字典 | 判断两个字符串是否为变位词 |
characterCounts
函数计算字符频率分布,比较两个字典 | 判断两个字符串是否为变位词的场景 |
| 字典 | 计算Scrabble™得分 | 字典
points
将字母映射到得分 | 根据字母得分规则计算单词得分的场景 |
| 字典 | 创建随机宾果卡 |
createCard
函数为每个字母生成随机数,
displayCard
函数显示宾果卡 | 创建随机宾果卡的场景 |
4. 流程图示例
以下是埃拉托斯特尼筛法求素数的mermaid流程图:
graph TD;
A[开始] --> B[输入限制范围limit];
B --> C[创建包含0到limit的整数列表nums];
C --> D[将nums[1]标记为0];
D --> E[p = 2];
E --> F{p < limit};
F -- 是 --> G[将p的倍数标记为0];
G --> H[寻找下一个未标记的数p];
H --> F;
F -- 否 --> I[遍历nums,打印未标记的数];
I --> J[结束];
5. 操作步骤总结
5.1 列表操作步骤总结
-
排序操作
:
- 创建一个空列表用于存储用户输入的数据。
- 通过循环读取用户输入的数据并添加到列表中。
-
使用
sort()方法对列表进行排序。 - 遍历排序后的列表并显示结果。
-
异常值移除操作
:
- 创建一个空列表用于存储用户输入的数据。
- 通过循环读取用户输入的数据并添加到列表中。
- 检查数据数量是否足够。
- 如果足够,创建一个排序后的列表副本。
-
通过
pop()方法移除最大和最小的异常值。 - 显示移除异常值后的结果和原始数据。
5.2 字典操作步骤总结
-
反向查找操作
:
- 定义一个字典存储键值对。
-
定义
reverseLookup函数,遍历字典,找出所有映射到指定值的键。 -
调用
reverseLookup函数进行测试并显示结果。
-
计算唯一字符数量操作
:
- 读取用户输入的字符串。
-
遍历字符串中的每个字符,将其作为键添加到字典中,并将值设为
True。 - 打印字典的键数量,即字符串中唯一字符的数量。
6. 注意事项
在使用列表和字典时,还需要注意以下几点:
-
列表操作注意事项
:
- 在使用
pop()
方法移除元素时,要注意索引越界的问题。
- 在生成随机数时,要确保随机数的范围和唯一性。
- 在处理字符串分词时,要考虑表达式的合法性。
-
字典操作注意事项
:
- 在进行反向查找时,要注意值可能对应多个键。
- 在使用字典计算唯一字符数量时,字典的值可以是任意值,只要能保证键的唯一性。
通过对这些练习题的学习和实践,我们可以更好地掌握Python中列表和字典的使用,提高编程能力,解决更多实际问题。希望大家在实际应用中能够灵活运用这些知识,创造出更优秀的程序!
超级会员免费看
2078

被折叠的 条评论
为什么被折叠?



