2011-03-28 4 views
4

멋지게 연주 :이 세 가지를 예상 할 때 나는 단지 그것을 두 개의 인수를주는거야 때문에파이썬은, 튜플 인수는 다른 예를 들어

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

printstuff(mytuple," How are you") 

이 자연스럽게 형식 오류 함께 충돌합니다.

모든 것을 확장하는 것보다 tuple을 효과적으로 '분할하는'간단한 방법이 있습니까? 마찬가지로 :

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

+0

원래 예제의 내용과 일치시킵니다. – yan

+4

하지만 'mytuple'은 이미 2 튜플입니다. 그래서 명백한 이유없이 2-tuple을 효과적으로 복사합니다. – ncoghlan

0

당신이 시도 할 수 :

def printstuff(*args): 
    print args 

또 다른 옵션은 새로운 namedtuple 컬렉션 형식을 사용하는 것입니다.

+1

하지만'args'는 튜플과 문자열로 ("hello", "world", "how?") 될 것입니다. –

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

실제로는 인수의 순서를 변경하지 않고 수행 할 수 있습니다. 먼저 문자열을 튜플로 변환하고 튜플에 추가 한 다음 더 큰 튜플을 인수로 전달해야합니다.

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