Python 中星号的本质及其使用方式

2019-02-28  本文已影响0人  苍简

翻译:Python 开发者 - 一汀, 英文:Trey Hunner

http://blog.jobbole.com/114655/

原文地址:https://mp.weixin.qq.com/s?__biz=MzA4MjEyNTA5Mw==&mid=2652569153&idx=1&sn=57b34413de84ec876976cad5cab520bc&chksm=8464d60bb3135f1d5fb724022952b9ef1c366a42eac1bc475a8ae5341916e4670c029e74cb9d&mpshare=1&scene=1&srcid=#rd

解压列表

>>> fruits = ['lemon', 'pear', 'watermelon', 'tomato']

>>> print(fruits[0], fruits[1], fruits[2], fruits[3])

lemon pear watermelon tomato

>>> print(*fruits)

lemon pear watermelon tomato
>>> date_info = {'year': "2020", 'month': "01", 'day': "01"}

>>> filename = "{year}-{month}-{day}.txt".format(**date_info)

>>> filename '2020-01-01.txt' 
>>> fruits = ['lemon', 'pear', 'watermelon', 'tomato']

>>> numbers = [2, 1, 3, 4, 7]

>>> print(*numbers, *fruits)

2 1 3 4 7 lemon pear watermelon tomato 

运算符也有另外一个功能:我们在定义函数时,可以使用 捕获传进函数的任何关键字参数到一个字典当中:

def tag(tag_name, **attributes):

    attribute_list = [

        f'{name}="{value}"'

        for name, value in attributes.items()

    ]    

    return f"<{tag_name} {' '.join(attribute_list)}>"

** 将捕获我们传入这个函数中的任何关键字参数,并将其放入一个字典中,该字典将引用attributes参数。

>>> tag('a', href="http://treyhunner.com")

'<a href="http://treyhunner.com">'

>>> tag('img', height=20, width=40, src="face.jpg")

'<img height="20" width="40" src="face.jpg">'

元组拆包

>>> fruits = ['lemon', 'pear', 'watermelon', 'tomato']

>>> first, second, *remaining = fruits

>>> remaining

['watermelon', 'tomato']

>>> first, *remaining = fruits

>>> remaining

['pear', 'watermelon', 'tomato']

>>> first, *middle, last = fruits

>>> middle

['pear', 'watermelon']

字典操作

>>> date_info = {'year': "2020", 'month': "01", 'day': "01"}

>>> track_info = {'artist': "Beethoven", 'title': 'Symphony No 5'}

>>> all_info = {**date_info, **track_info}

>>> all_info

{'year': '2020', 'month': '01', 'day': '01', 'artist': 'Beethoven', 'title':'Symphony No 5'}


>>> date_info = {'year': '2020', 'month': '01', 'day': '7'}

>>> event_info = {**date_info, 'group': "Python Meetup"}

>>> event_info

{'year': '2020', 'month': '01', 'day': '7', 'group': 'Python Meetup'}
>>> event_info = {'year': '2020', 'month': '01', 'day': '7', 'group':'Python Meetup'}

>>> new_info = {**event_info, 'day': "14"}

>>> new_info

{'year': '2020', 'month': '01', 'day': '14', 'group': 'Python Meetup'}


上一篇下一篇

猜你喜欢

热点阅读