简体   繁体   中英

How do I search for an element in a list using an element in another list?

These are the lists I have written in my code:

book_codes = [1 , 2 , 3 , 10] 
book_names = ["Harry Potter" , "Game of Thrones" , "Star Wars" , "War of the Worlds"] 
book_categories = ["Fantasy" , "Fantasy" , "Science-fiction" , "Science-fiction"]

I am trying to create a function where the user types the code of a book into the function below, and then the function reads out information related to that book code. This is all I've come up with so far:

book_code = int(input("Please enter book code: "))
index = book_codes.index(book_code)

For example, if the user types '2' into the function, the function should print something along the lines of:

Code: 2 - Title: Game of Thrones - Category: Fantasy

Use a dataclass and a dict .

from dataclasses import dataclass


@dataclass
class Book:
    id: int  # Not clear if this is necessary
    name: str
    category: str


book_codes = [1 , 2 , 3 , 10] 
book_names = ["Harry Potter" , "Game of Thrones" , "Star Wars" , "War of the Worlds"] 
book_categories = ["Fantasy" , "Fantasy" , "Science-fiction" , "Science-fiction"]

books = {id: Book(id, name, category) for id, name, category in zip(book_codes, book_names, book_categories)}


book_code = int(input("Please enter book code: "))
book = books[book_code]

better to store information in dictionary than in list format

book_codes = [1 , 2 , 3 , 10] 
book_names = ["Harry Potter" , "Game of Thrones" , "Star Wars" , "War of the Worlds"] 
book_categories = ["Fantasy" , "Fantasy" , "Science-fiction" , "Science-fiction"]


dataset = { code: {'book_name':book_names[index],'book_category':book_categories[index]} for index, code in enumerate(book_codes)}


"""
dataset 

    {1: {'book_name': 'Harry Potter', 'book_category': 'Fantasy'},
 2: {'book_name': 'Game of Thrones', 'book_category': 'Fantasy'},
 3: {'book_name': 'Star Wars', 'book_category': 'Science-fiction'},
 10: {'book_name': 'War of the Worlds', 'book_category': 'Science-fiction'}}

"""

input_code = int(input("enter book input code : " ))

if input_code in dataset:
    for k, v in dataset[input_code].items():
        print("{} = {}".format(k, v))
else:
    print("invalid input code")

Instead of using 3 lists use 1 dictionary by code:

You can generate it by hand or use this line:

books_by_code = {code: {"name": name, "category": category} for code, name, category in zip(book_codes, book_names, book_categories)}

And now you can find a book by its code easily using this dictionary:

{1: {'category': 'Fantasy', 'name': 'Harry Potter'},
 2: {'category': 'Fantasy', 'name': 'Game of Thrones'},
 3: {'category': 'Science-fiction', 'name': 'Star Wars'},
 10: {'category': 'Science-fiction', 'name': 'War of the Worlds'}}

To find the category of a book with code = 2:

books_by_code[2]["category"] # Fantasy

To print information in your format:

>>> code = 2 # change to user input
>>> category = books_by_code[code]["category"]
>>> name = books_by_code[code]["name"] # should probably be "title"
>>> print("Code: {} - Title: {} - Category: {}".format(code, name, category))
Code: 2 - Title: Game of Thrones - Category: Fantasy

Assuming that you will have unique book code, It can be solved using,

  • Zip
  • Filter
  • Lambda
  • List

List : The list() constructor take in a iterable and returns a list consisting of iterable's items.

Zip: The zip() function returns an iterator of tuples based on the iterable objects.

list1 = [1, 2, 3]
list2 = ['one', 'two', 'three']

print (list(zip(list1, list2)))

# Output : [(1, 'one'), (2, 'two'), (3, 'three')]

Lambda : A lambda function is a small anonymous function.

x = lambda a : a + 10
print(x(5))

# Output : 15

Filter : The filter() method filters the given sequence with the help of a function that tests each element in the sequence to be true or not.

seq = [0, 1, 2, 3, 5, 8, 13] 
  
# result contains even numbers of the list 
result = filter(lambda x: x % 2 == 0, seq) 
print(list(result)) 

# Output : [0, 2, 8]

Coming to you problem the solution would be,

book_codes = [1 , 2 , 3 , 10] 
book_names = ["Harry Potter" , "Game of Thrones" , "Star Wars" , "War of the Worlds"] 
book_categories = ["Fantasy" , "Fantasy" , "Science-fiction" , "Science-fiction"]

book_code = int(input("Please enter book code: "))
result = list(filter(lambda x  : x[0] == book_code ,zip(book_codes,book_names,book_categories)))[0]

print ("Code: {} - Title: {} - Category: {}".format(result[0], result[1], result[2]))

# Output : Code: 2 - Title: Game of Thrones - Category: Fantasy

Hope this was helpful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM