Reputation: 11
I'm pulling in a text file as a multidimensional array and giving the user a choice to pick one of the items and it is stored in another array. I'm trying to figure out how to find the index of the first array with the elements in the second.
Code:
with open("books.txt") as b:
books = b.readlines()[7:]
books = [x.strip() for x in books]
books = [x.split(",") for x in books]
def welcome():
print("Welcome to the Bookstore")
global name
name = input("What is your name? ")
print("Our current list of books are: ")
inventory()
def choice():
select = input("Which books would you like? (ID):\n")
global chosen
chosen = []
flag = "y"
while flag == "y":
chosen.append(select)
flag = input("Would you like to add more books to your cart? (y/n): ")
print(chosen)
for chosen in books:
books.index(chosen[0])
def inventory():
length = len(books)
for i in range(length):
print(books[i][0], books[i][1].strip(), ("$" + books[i][2]).replace(" ", ""))
choice()
def receipt():
print("Thank you", name)
welcome()
Text File:
To add books to your store please have a new book on each line, and use the format ItemNumber,BookName,BookPrice an example would be as follows: B142, Prelude to Programing, 5.25 Please start entering books under the heading Books Available. Thank You Books Available: B12, Prelude to Programing, 5.25 B13, Lazy Python, 10.25 B14, Coding for Dummys, 19.25
I have tried
for chosen in books:
books.index(chosen[0])
If i select B12
, I want the result to be 0
0
for the index numbers.
Upvotes: 1
Views: 262
Reputation: 5372
Issues:
chosen
in the line for chosen in books:
.select
colors in my editor as a module select exists. You may want to change the name.Replace choice() with this change.
def choice():
global chosen
chosen = []
while True:
select = input("Which books would you like? (ID):\n")
chosen.append(select)
flag = input("Would you like to add more books to your cart? (y/n): ")
if flag != 'y':
break
print(chosen)
index = []
for item in chosen:
for idx, book in enumerate(books):
if item == book[0]:
index.append([idx, 0])
print('index:', index)
The index list contains i.e. [[2, 0], ...]
The 2 being the index to find the book in books. The 0 being the index of the book id. If the result not exactly what you want, you can make the any changes needed.
Storing the book ID means searching later. You could store the index of the book instead.
i.e.
def choice():
global chosen
chosen = []
while True:
select = input("Which books would you like? (ID):\n")
# Get the index of the selected book in books.
for idx, book in enumerate(books):
if select == book[0]:
chosen.append(idx)
break
flag = input("Would you like to add more books to your cart? (y/n): ")
if flag != 'y':
break
print(chosen)
# [[0, 0], ...]
result = [[idx, 0] for idx in chosen]
print(result)
This function is storing the index of the book chosen rather than the ID of the book ID as it is more convenient to use the index later as the use of list comprehension shows at the end.
Upvotes: 1