python 炫技

2021-11-22  本文已影响0人  hehehehe
条件语句

<on_true> if <condition> else <on_false>

msg1 = "已成年" if age1 > 18 else "未成年"

<condition> and <on_true> or <on_false>

msg1 = age1 > 18 and "已成年" or "未成年"

(<on_true>, <on_false>)[condition]

msg1 = ("未成年", "已成年")[age1 > 18]

{True: <on_true>, False: <on_false>}[<condition>]

msg1 = {True: "已成年", False: "未成年"}[age1 > 18]
连接列表

使用 + 对多个列表进行相加
使用 * 可以解包列表,使用 ** 可解包字典
在字典中,使用 update 可实现原地更新,而在列表中,使用 extend 可实现列表的自我扩展

list01 + list02 + list03
list(chain(list01, list02))
[*list01, *list02]
合并字典
full_profile01 = {**profile, **ext_info}
profile.update(ext_info)
dict(itertools.chain(profile.items(), ext_info.items()))
dict(ChainMap(profile, ext_info))
上一篇下一篇

猜你喜欢

热点阅读