Python的switch替换方案、列表推导式、字典推导式

switch替换方案


day = 8

def get_sunday():
    return 'Sunday'

def get_monday():
    return 'Monday'

def get_tuesday():
    return 'Tuesday'

def get_default():
    return 'Unkown'

switcher = {
    0: get_sunday,
    1: get_monday,
    2: get_tuesday
}

day_name = switcher.get(day, get_default)()
print(day_name)

列表推导式

# 列表推导式
# 集合推导式
# set 也可以被推导
# dict

a = [1,2,3,4,5,6,7,8]
aa = {1,2,3,4,5,6,7,8}
aaa = (1,2,3,4,5,6,7,8)

b = [i**2 for i in a]
c = [i**2 for i in a if i >= 5]
print(b)
print(c)

bb = {i**2 for i in aa}
bbb = [i**2 for i in aaa]
print(bb)
print(bbb)

字典推导式


students = {
    '张三': 18,
    '李四': 22,
    '王五': 16
}

b = [key for key,value in students.items()]
bb = {value:key for key,value in students.items()}
print(b) # ['张三', '李四', '王五']
print(bb) # {18: '张三', 22: '李四', 16: '王五'}

# 不推荐元组
c = (key for key,value in students.items())
for x in c:
    print(x)
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇