鍍金池/ 問答/PHP  Python/ python * 操作符拆解字典變量

python * 操作符拆解字典變量

d = {"name": "Jim", "gender": "male", "age": 20}
print(*d)

為什么這段代碼的運行結果是:

name gender age
[Finished in 0.1s]

但,我單獨運行*d,就會報錯:SyntaxError: can't use starred expression here

*d

請問,是什么原因?

回答
編輯回答
蟲児飛

你單獨運行 *d 是想達到什么用處?

這篇文章或許對你有些幫助
https://segmentfault.com/p/12...

2017年3月28日 11:27
編輯回答
哚蕾咪
  • *** 只在“傳參”時才有用。
  • * 處理“順序參數(shù)”,比如 f(1,2,3) ,可以是 f(*[1,2,3]) 。
  • ** 處理“關鍵詞參數(shù)”,比如 f(a=1, b=2, c=3) , 可以是 f(**{'a':1, 'b': 2, 'c': 3})

至于你說的問題,本質上,在 Python3 中, * 后面需要的是一個 sequence ,更準備地說,是一個 iterable 的對象:

# -*- coding: utf-8 -*-


class A(object):
    l = [1,2,3]

    def __init__(self):
        self.n = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self.n >= len(self.l):
            raise StopIteration()

        n = self.l[self.n]
        self.n += 1
        return n


print(*A())

而你代碼中的 d ,是一個 dict ,自然是一個可以 iterable 的對象。

2018年3月27日 10:42