简体   繁体   English

我可以在python中将这两个几乎相同的函数合二为一吗?

[英]Can I turn these two almost identical functions into one in python?

I have these two functions which are nearly identical apart from the if statement in search_genre, is there any way to combine them into one?我有这两个函数,除了 search_genre 中的 if 语句之外几乎相同,有什么方法可以将它们合二为一?

The books variable is a dictionary where each value is a list of dictionaries, ie: book 变量是一个字典,其中每个值都是一个字典列表,即:

books = {'Genre1':[{name:value, author:value}, {dict}], 'Genre2':[{dict}], and so on}书籍 = {'Genre1':[{name:value, author:value}, {dict}], 'Genre2':[{dict}],依此类推}

view_library() prints all the books and search_genre() takes a user input to print all books of a specific genre view_library() 打印所有书籍,search_genre() 接受用户输入以打印特定类型的所有书籍

def view_library():
    for genre in books:
        print(f'Genre: {genre}')
        for book in books[genre]:
            for key, value in book.items():
                print(f"{key.title()} : {value.title()}")
            print()


def search_genre(genre_type):
    for genre in books:
        if genre_type == genre:
            print(f'{genre_type}:')
            for book in books[genre_type]:
                for key, value in book.items():
                    print(f"{key.title()} : {value.title()}")
                print()

Try:尝试:

def search_genre(genre_type=None):
    for genre in books:
        if genre_type is None or genre_type == genre:
            print(f'{genre_type}:')
            for book in books[genre_type]:
                for key, value in book.items():
                    print(f"{key.title()} : {value.title()}")
                print()

The difference between the 2 functions is that in the first, all genres are processed, while in the second only the chosen on is.这两个函数的区别在于,第一个函数处理所有类型,而第二个函数仅处理所选类型。

The key is the if statement that determines whether the genre is printed: right now, it only fires if the genre matches the provided genre.关键是确定是否打印流派的if语句:现在,只有当流派与提供的流派匹配时才会触发。 We can add an or so that it also fires if no genre_type is provided.我们可以添加一个or以便在没有提供流派类型时它也会触发。 Now, if we call the function without a genre_type argument, it will print all genres:现在,如果我们调用没有genre_type参数的函数,它将打印所有流派:

def search_genre(genre_type=None):
    for genre in books:
        if not genre_type or genre_type == genre:
            print(f'{genre_type}:')
            for book in books[genre_type]:
                for key, value in book.items():
                    print(f"{key.title()} : {value.title()}")
                print()

Since you don't provide a MCVE of data, here's a simplified example with data to show how it works:由于您没有提供数据的 MCVE,这里有一个简单的数据示例来展示它是如何工作的:

def test(x=None):
    for y in z:
        if not x or x == y:
            print(y)

z = [1,2,3,4,5,6]

test()
1
2
3
4
5
6

test(5)
5

Start by implementing filter_by_genre using a filter.首先使用过滤器实现filter_by_genre It's basically the same as search_genre .它与search_genre基本相同。

def filter_by_genre(genre_type):
    for genre in filter(lambda x: x == genre_type, books):
        print(f'{genre_type}:')
        for book in books[genre]:
            for key, value in book.items():
                print(f"{key.title()} : {value.title()}")
            print()

filter_by_genre("mystery")

Now, instead of passing a genre as an argument, pass a predicate:现在,不是将类型作为参数传递,而是传递谓词:

def filter_by_genre(p):
    for genre in filter(p, books):
        print(f'{genre_type}:')
        for book in books[genre]:
            for key, value in book.items():
                print(f"{key.title()} : {value.title()}")
            print()

filter_by_genre(lambda x: x == "mystery")

Both view_library and search_genre can then be implemented in terms of filter_by_genre : view_librarysearch_genre都可以根据filter_by_genre来实现:

def view_library():
    return filter_by_genre(lambda x: True)


def search_genre(genre_type):
    return filter_by_genre(lambda x: x == genre_type)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 两个(几乎)相同的 View.py 函数表现不同 - Two (Almost) Identical View.py Functions Behaving Differently 两个几乎相同的代码,一个有效,另一个无效 - Two almost identical codes, one works but the other doesn't 在 Python 3 中的 csv.DictReader 中合并两个几乎相同的行 - Merge two almost identical rows in a csv.DictReader in Python 3 两个几乎相同的python文件提供不同的输出 - Two almost identical python files giving different outputs 合并两个几乎相同的字符串 - Merging two almost identical strings 使用repr()时,两个看似相同的unicode字符串会有所不同,但我该如何解决这个问题呢? - Two seemingly identical unicode strings turn out to be different when using repr(), but how can I fix this? 如何组合两个几乎相同的功能但有效地返回不同的 output - How can I combine two almost same functions but return different output efficiently 我可以命名 2 个与前一个相同的后续列吗? (Python) - Can I name 2 subsequent columns identical like the previous one? (python) 我有两个几乎相同的“for循环”函数,但只有一个有效。 这是为什么? - I have two practically identical “for loop” functions, but only one of them works. Why is that? 只返回一个字符串而不是两个几乎相同的 - Return only a string instead of two almost identical
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM