gpt4 book ai didi

python - 使用另一个数组搜索一个数组

转载 作者:太空宇宙 更新时间:2023-11-03 14:23:55 24 4
gpt4 key购买 nike

我将一个文本文件作为多维数组拉入,并让用户选择其中一个项目并将其存储在另一个数组中。我正在尝试找出如何使用第二个数组中的元素查找第一个数组的索引。

代码:

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()

文本文件:

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

我已经尝试过

for chosen in books:
books.index(chosen[0])

如果我选择 B12,我希望索引号的结果为 0 0

最佳答案

问题:

  1. 您正在覆盖 for selected in books: 行中的 chosen
  2. 循环提示更多书籍只是在输入 y 获取更多书籍时附加最后选择的书籍 ID。
  3. 我的编辑器中的单词select颜色作为模块 select存在。您可能想更改名称。

用此更改替换 choice()。

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)

索引列表包含,即[[2, 0], ...]

2是在书本中查找该书的索引。0 是图书 ID 的索引。如果结果不完全是您想要的,您可以进行所需的任何更改。

<小时/>

存储图书 ID 意味着以后可以进行搜索。您可以存储该书的索引。

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)

此函数存储所选书籍的索引,而不是书籍 ID 的 ID,因为稍后使用索引会更方便,如末尾所示的列表理解的使用。

关于python - 使用另一个数组搜索一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47762639/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com