2011-03-28 26 views
4

例如很好地發揮:Python中,元組參數與他人

mytuple = ("Hello","World") 
def printstuff(one,two,three): 
    print one,two,three 

printstuff(mytuple," How are you") 

這自然崩潰了與類型錯誤,因爲我只給了它兩個參數,它需要三個。

有沒有一種簡單的方法來有效地「分裂」一個元組,而不是擴展一切?像:

printstuff(mytuple[0],mytuple[1]," How are you") 

回答

4

不是不改變參數排序或切換到命名參數。

這裏是命名參數的替代方案。

printstuff(*mytuple, three=" How are you") 

這是開關順序的選擇。

def printstuff(three, one, two): 
    print one, two, three 

printstuff(" How are you", *mytuple) 

這可能是非常可怕的。

3

嘗試以下操作:

printstuff(*(mytuple[0:2]+(" how are you",))) 
+0

爲什麼要分片元組? – ncoghlan 2011-03-29 01:50:08

+0

匹配原始示例中的元素。 – yan 2011-03-29 02:31:34

+4

但是'mytuple'已經是2元組了。所以你沒有明顯的原因切片2元組(有效地複製它)。 – ncoghlan 2011-03-29 03:14:12

0

你可以嘗試:

def printstuff(*args): 
    print args 

另一種選擇是使用新的namedtuple集合類型。

+1

但'args'會作爲元組和字符串((「你好」,「世界」,「你好嗎」))。 – 2011-03-28 20:51:14

6

有點兒......你可以這樣做:

>>> def fun(a, b, c): 
...  print(a, b, c) 
... 
>>> fun(*(1, 2), 3) 
    File "<stdin>", line 1 
SyntaxError: only named arguments may follow *expression 
>>> fun(*(1, 2), c=3) 
1 2 3 

正如你所看到的,你可以做你想做幾乎只要您符合條件後,它的到來,其名稱的任何爭論什麼。

1
mytuple = ("Hello","World") 

def targs(tuple, *args): 
    return tuple + args 

def printstuff(one,two,three): 
    print one,two,three 

printstuff(*targs(mytuple, " How are you")) 
Hello World How are you 
0

實際上,可以在不改變參數順序的情況下進行。首先,你必須將你的字符串轉換爲一個元組,將它添加到你的元組mytuple,然後將更大的元組作爲參數傳遞。

printstuff(*(mytuple+(" How are you",))) 
# With your example, it returns: "Hello World How are you"