簡體   English   中英

多個參數解包

[英]Multiple Argument Unpacking

我正在學習參數解包並發現它是一個有用的功能,我們可以直接檢索列表中的值而無需編寫額外的代碼行。 例如,

def simplePrint(x,y):
      print x,y

myList = [3,4]

>>>simplePrint(*myList) #directly retrieve the values in myList ,storing the values in x & y and printing
3 4

但是如果列表中有三個,四個,十個或一百個值,那么我們就不能在函數中傳遞那么多的參數。所以,為此我嘗試了這個:

def simplePrint(*args):
      print args


myList = [3,4,5]

>>>simplePrint(*myList)
(3,4,5)

這是一個元組

所以我的問題是我做錯了什么? 或者有沒有辦法像第一個例子那樣直接檢索值。

提前致謝 :)

使用print作為函數(使用__future__ - Future語句定義

>>> from __future__ import print_function
>>>
>>> def simplePrint(*args):
...       print(*args)
...
>>> myList = [3,4,5]
>>> simplePrint(*myList)
3 4 5

或者只是調用print功能:

>>> print(*myList)
3 4 5

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM