#python #list #function #dictionary
#python #Список #функция #словарь
Вопрос:
Вопрос, на который я пытаюсь ответить
- Запросите, доступно ли название книги, и укажите вариант (а) увеличения уровня запасов или (б) уменьшения уровня запасов из-за продажи. Если уровень запасов уменьшен до нуля, укажите пользователю, что книга в настоящее время отсутствует на складе.
Это текстовый файл
#Listing showing sample book details
#AUTHOR, TITLE, FORMAT, PUBLISHER, COST?, STOCK, GENRE
P.G. Wodehouse, Right Ho Jeeves, hb, Penguin, 10.99, 5, fiction
A. Pais, Subtle is the Lord, pb, OUP, 12.99, 2, biography
A. Calaprice, The Quotable Einstein, pb, PUP, 7.99, 6, science
M. Faraday, The Chemical History of a Candle, pb, Cherokee, 5.99, 1, science
C. Smith, Energy and Empire, hb, CUP, 60, 1, science
J. Herschel, Popular Lectures, hb, CUP, 25, 1, science
C.S. Lewis, The Screwtape Letters, pb, Fount, 6.99, 16, religion
J.R.R. Tolkein, The Hobbit, pb, Harper Collins, 7.99, 12, fiction
C.S. Lewis, The Four Loves, pb, Fount, 6.99, 7, religion
E. Heisenberg, Inner Exile, hb, Birkhauser, 24.95, 1, biography
G.G. Stokes, Natural Theology, hb, Black, 30, 1, religion
И это код, который у меня есть до сих пор
def Task5():
again = 'y'
while again == 'y':
desc = input('Enter the title of the book you would like to search for: ')
for bookrecord in book_list:
if desc in book_list:
print('Book found')
else:
print('Book not found')
break
again = input('nWould you like to search again(press y for yes)').lower()
у меня уже есть функция, которая считывает данные из текстового файла:
book_list = []
def readbook():
infile = open('book_data_file.txt')
for row in infile:
start = 0 # used to start at the beginning of each line
string_builder = []
if not(row.startswith('#')):
for index in range(len(row)):
if row[index] ==',' or index ==len(row)-1:
string_builder.append(row[start:index])
start = index 1
book_list.append(string_builder)
infile.close()
У кого-нибудь есть идея о том, как я выполняю эту задачу? 🙂
Ответ №1:
-
- Получите заголовки из
book_list
переменной.
-
titles = [data[1].strip() for data in book_list]
- Получите заголовки из
-
- Удалите все пробелы из
desc
переменной.
-
desc = desc.strip()
- Например, если я ищу
Popular Lectures
book, но если я набираюPopular Lectures
, я не могу найти его вbook_list
, поэтому вы должны удалить белые символы из ввода.
- Удалите все пробелы из
-
- Если книга доступна, затем получите название книги и стоимость акций из
book_list
-
info = [(title, int(book_list[idx][5].strip())) for idx, title in enumerate(titles) if desc in title][0] bk_nm, stock = info
- Если книга доступна, затем получите название книги и стоимость акций из
-
- Выведите текущую ситуацию
-
if stock == 0: print("{} is currently not avail".format(bk_nm)) else: print("{} is avail w/ stock {}".format(bk_nm, stock))
Пример:
Enter the title of the book you would like to search for: Popular Lectures
Popular Lectures is avail w/ stock 1
Would you like to search again(press y for yes)y
Enter the title of the book you would like to search for: Chemical
The Chemical History of a Candle is avail w/ stock 1
Would you like to search again(press y for yes)n
Код:
book_list = []
def task5():
titles = [data[1].strip() for data in book_list]
again = 'y'
while again == 'y':
desc = input('Enter the title of the book you would like to search for: ')
desc = desc.strip() # Remove any white space
stock = [int(book_list[idx][5].strip()) for idx, title in enumerate(titles) if desc in title][0]
if stock == 0:
print("{} is currently not avail".format(desc))
else:
print("{} is avail w/ stock {}".format(desc, stock))
again = input('nWould you like to search again(press y for yes)').lower()
def read_txt():
infile = open('book_data_file.txt')
for row in infile:
start = 0 # used to start at the beginning of each line
string_builder = []
if not (row.startswith('#')):
for index in range(len(row)):
if row[index] == ',' or index == len(row) - 1:
string_builder.append(row[start:index])
start = index 1
book_list.append(string_builder)
infile.close()
if __name__ == '__main__':
read_txt()
task5()