【讀碼】python中的小星星*用法示例

【讀碼】python中的小星星*用法示例

讀懂代碼很難的,比寫代碼還難,但也是最節約時間最好的學習方式之一。今天咱們經過讀代碼來了解一下python中的 * 或者 * 。經過讀代碼,幫助咱們學習python中的 功用。這裏我一共列了8個demo,都不是很那,相信你們應該都能根據運行結果推導出星號的功能。python

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

more_numbers = [*numbers, 11, 18]
more_numbers

運行結果markdown

[2, 1, 3, 4, 7, 11, 18]

我在學習這塊知識的時候,因爲沒有比較專業化的命名方式說明每一種用法的名字,因此我就將代碼列在下面,供你們學習。dom

demo1
當咱們調用一個函數時, * 操做能將 可迭代對象傳入 一個調用的函數中去,以下ide

fruits = ['lemon', 'pear', 'watermelon', 'tomato']
print(fruits[0], fruits[1], fruits[2], fruits[3])
print(*fruits)

運行結果函數

lemon pear watermelon tomato
lemon pear watermelon tomato
demo2

咱們再來看一個例子-實現矩陣轉置學習

def transpose_list(list_of_lists):
    return [list(row) 
            for row in zip(*list_of_lists)]

matrix = [[1, 4, 7], 
          [2, 5, 8], 
          [3, 6, 9]]

transpose_list(matrix)

運行結果ui

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
demo3

* 操做與 相似,可是傳入的是關鍵詞參數。code

date_info = {'year': "2020", 'month': "01", 'day': "01"}
filename = "{year}-{month}-{day}.txt".format(**date_info)
filename

運行結果orm

'2020-01-01.txt'

demo4
當咱們定義函數時 , * 操做能夠將函數設置成任意個數的參數。例如對象

from random import randint

def roll(*dice):
    #randint(1, die) 在1到die中隨機生成一個整數
    #最後再加總
    return sum(randint(1, die) for die in dice)

print(roll(20))
print(roll(6))
print(roll(6, 6, 6))

運行結果

1
2
12

demo5

def tag(tag_name, **attributes):
    attribute_list = [
        f'{name}="{value}"'
        for name, value in attributes.items()
    ]
    return f"<{tag_name} {' '.join(attribute_list)}>"

print(tag('a', href="http://treyhunner.com"))
print(tag('img', width="40", src="face.jpg"))

運行結果

<a rel="nofollow" href="http://treyhunner.com">
<img width="40" src="face.jpg">

dmeo6

fruits = ['lemon', 'pear', 'watermelon', 'tomato']
first, second, *remaining = fruits
remaining

運行結果

['watermelon', 'tomato']

demo7

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'}

demo8

def go(**kwargs):
    #kwargs在函數內是一個字典
    for k, v in kwargs.items():
        print(k,v)

go(a=1, b=2, c=3)

運行結果
**
a 1
b 2
c 3

**

相關文章
相關標籤/搜索