Programming

파이썬에서 함수에서 두 값을 어떻게 반환 할 수 있습니까?

procodes 2020. 5. 14. 20:51
반응형

파이썬에서 함수에서 두 값을 어떻게 반환 할 수 있습니까?


함수에서 두 개의 개별 변수로 두 개의 값을 반환하고 싶습니다. 예를 들면 다음과 같습니다.

def select_choice():
    loop = 1
    row = 0
    while loop == 1:
        print('''Choose from the following options?:
                 1. Row 1
                 2. Row 2
                 3. Row 3''')

        row = int(input("Which row would you like to move the card from?: "))
        if row == 1:
            i = 2
            card = list_a[-1]
        elif row == 2:
            i = 1
            card = list_b[-1]
        elif row == 3:
            i = 0
            card = list_c[-1]
        return i
        return card

그리고 나는이 값들을 별도로 사용할 수 있기를 원합니다. 을 사용하려고하면 return i, carda가 반환 tuple되고 이것이 내가 원하는 것이 아닙니다.


두 개의 값을 반환 할 수 없지만 호출 후 a tuple또는 a를 반환 list하고 압축을 풀 수 있습니다.

def select_choice():
    ...
    return i, card  # or [i, card]

my_i, my_card = select_choice()

온라인 return i, card i, card은 튜플을 만드는 것을 의미합니다. 과 같이 괄호를 사용할 수도 return (i, card)있지만 튜플은 쉼표로 작성되므로 괄호는 필수가 아닙니다. 그러나 parens를 사용하여 코드를 더 읽기 쉽게 만들거나 튜플을 여러 줄로 나눌 수 있습니다. line에도 동일하게 적용됩니다 my_i, my_card = select_choice().

두 개 이상의 값을 반환하려면 명명 된 tuple 사용을 고려하십시오 . 함수 호출자가 이름으로 리턴 된 값의 필드에 액세스 할 수있게되므로 더 읽기 쉽습니다. 인덱스로 튜플의 항목에 계속 액세스 할 수 있습니다. 예를 들어, Schema.loadsMarshmallow 프레임 워크에서는 a UnmarshalResulta 반환 합니다 namedtuple. 그래서 당신은 할 수 있습니다 :

data, errors = MySchema.loads(request.json())
if errors:
    ...

또는

result = MySchema.loads(request.json())
if result.errors:
    ...
else:
    # use `result.data`

다른 경우에는 dict함수에서 a 반환 할 수 있습니다.

def select_choice():
    ...
    return {'i': i, 'card': card, 'other_field': other_field, ...}

그러나 데이터를 래핑하는 유틸리티 클래스의 인스턴스를 반환하는 것이 좋습니다.

class ChoiceData():
    def __init__(self, i, card, other_field, ...):
        # you can put here some validation logic
        self.i = i
        self.card = card
        self.other_field = other_field
        ...

def select_choice():
    ...
    return ChoiceData(i, card, other_field, ...)

choice_data = select_choice()
print(choice_data.i, choice_data.card)

함수에서 두 개의 개별 변수로 두 개의 값을 반환하고 싶습니다.

발신 측에서 어떤 모습 일 것으로 기대하십니까? a = select_choice(); b = select_choice()함수를 두 번 호출하기 때문에 작성할 수 없습니다 .

Values aren't returned "in variables"; that's not how Python works. A function returns values (objects). A variable is just a name for a value in a given context. When you call a function and assign the return value somewhere, what you're doing is giving the received value a name in the calling context. The function doesn't put the value "into a variable" for you, the assignment does (never mind that the variable isn't "storage" for the value, but again, just a name).

When i tried to to use return i, card, it returns a tuple and this is not what i want.

Actually, it's exactly what you want. All you have to do is take the tuple apart again.

And i want to be able to use these values separately.

So just grab the values out of the tuple.

The easiest way to do this is by unpacking:

a, b = select_choice()

I think you what you want is a tuple. If you use return (i, card), you can get these two results by:

i, card = select_choice()

def test():
    ....
    return r1, r2, r3, ....

>> ret_val = test()
>> print ret_val
(r1, r2, r3, ....)

now you can do everything you like with your tuple.


def test():
    r1 = 1
    r2 = 2
    r3 = 3
    return r1, r2, r3

x,y,z = test()
print x
print y
print z


> test.py 
1
2
3

You can return more than one value using list also. Check the code below

def newFn():    #your function
  result = []    #defining blank list which is to be return
  r1 = 'return1'    #first value
  r2 = 'return2'    #second value
  result.append(r1)    #adding first value in list
  result.append(r2)    #adding second value in list
  return result    #returning your list

ret_val1 = newFn()[1]    #you can get any desired result from it
print ret_val1    #print/manipulate your your result

And this is an alternative.If you are returning as list then it is simple to get the values.

def select_choice():
    ...
    return [i, card]

values = select_choice()

print values[0]
print values[1]

참고URL : https://stackoverflow.com/questions/9752958/how-can-i-return-two-values-from-a-function-in-python

반응형