简体   繁体   English

if 和 elif 函数的 Python 列表推导式

[英]Python list comprehension for if and elif function

from datetime import date

a_dictionary = {"name" : "John", "age" : 35, "height" : 65}

dict_items = a_dictionary.items()


def month_selct(d):
    if date.today().month == 1:
        d = list(d)[:2]

    elif date.today().month == 2:
        d = list(d)[:2]

    elif date.today().month == 3:
        d = list(d)[:2]

month_selct(dict_items)

Can you help me with reduction this code?你能帮我减少这个代码吗? I want this function work with each month but its just an example for 3 of it我希望这个函数每个月都能使用,但它只是其中 3 个的一个例子

You can implement a switch logic in python with a dictionary:您可以使用字典在 python 中实现切换逻辑:

def month_selct(d):
    switch = {
        1 : list(d)[:2],
        2 : list(d)[:2],
        3 : list(d)[:2],
        11: list(d)[:2]
    }
    return switch[date.today().month]

print(month_selct(dict_items))

You can use a for loop to iterate through each month and check if that's the month you're in, as follows:您可以使用 for 循环遍历每个月并检查那是您所在的月份,如下所示:

def month_select(d):
    for m in range(1, 13):
        if date.today().month == m:
            d = list(d)[:2]

EDIT: you asked for a list comprehension solution编辑:您要求列表理解解决方案

d = [list(d)[:2] for m in range(1, 13) if date.today().month == m]

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

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