Home > Net >  How to print elements of a random list next to other elements in order?
How to print elements of a random list next to other elements in order?

Time:02-27

Can anyone help me figure out how to print elements of a randomly created list next to chosen numbers in order? The numbers are book names and the numbers that are random are book prices and I need those prices to be returned next to book names after you have chosen what books you are going to buy

Here is my code:

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)}')

It returns something like this:

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

I would like it to be more like:

Chosen books: 
2: 25
5: 12
7: 16

CodePudding user response:

You need to save the prices somewhere. A dictionary is a good container for this.

I also refractored a bit the code:

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]}')

Output:

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
  • Related