誰能幫我弄清楚如何按順序在所選數字旁邊列印隨機創建的串列的元素?數字是書名,亂數字是書價,在您選擇要購買的書后,我需要在書名旁邊回傳這些價格
這是我的代碼:
import random
print("Books for sale")
m = 25
price_list = []
for s in range(3, m 1):
price_list.append(s)
i = 0
books = 1
n = 10
book_list = []
while i < n:
prices = random.sample(price_list, 1)
print(f"{books}: {prices}")
i = 1
books = 1
print("Enter, which books are you going to buy (1 - 10) ==>")
numbers = [int(s) for s in input().split()]
print("Chosen books: ")
for el in range(len(numbers)):
print(f'{numbers[el]}: {price_list.count(el)}')
它回傳如下內容:
Books for sale
1: [8]
2: [25]
3: [5]
4: [24]
5: [12]
6: [24]
7: [16]
8: [3]
9: [21]
10: [13]
Enter, which books are you going to buy (1 - 10) ==>
2 5 7
Chosen books:
2: 0
5: 0
7: 0
我希望它更像:
Chosen books:
2: 25
5: 12
7: 16
uj5u.com熱心網友回復:
您需要在某處保存價格。字典是一個很好的容器。
我還重構了一點代碼:
import random
print("Books for sale")
m = 25
price_list = list(range(3, m 1))
n = 10
books = {}
for book in range(n):
price = random.sample(price_list, 1)[0]
print(f"{book}: {price}")
books[book] = price
print("Enter, which books are you going to buy (1 - 10) ==>")
numbers = [int(s) for s in input().split()]
print("Chosen books: ")
for n in numbers:
print(f'{n}: {books[n]}')
輸出:
Books for sale
0: 5
1: 10
2: 18
3: 11
4: 20
5: 25
6: 13
7: 23
8: 8
9: 18
Enter, which books are you going to buy (1 - 10) ==>
2 5 7
Chosen books:
2: 18
5: 25
7: 23
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/435237.html
