Programing

목록에서 Python append () 대 + 연산자가 다른 결과를 제공하는 이유는 무엇입니까?

lottogame 2020. 8. 20. 19:26
반응형

목록에서 Python append () 대 + 연산자가 다른 결과를 제공하는 이유는 무엇입니까?


왜이 두 작업은 (DO append()RESP. +) 다른 결과를?

>>> c = [1, 2, 3]
>>> c
[1, 2, 3]
>>> c += c
>>> c
[1, 2, 3, 1, 2, 3]
>>> c = [1, 2, 3]
>>> c.append(c)
>>> c
[1, 2, 3, [...]]
>>> 

마지막 경우에는 실제로 무한 재귀가 있습니다. c[-1]그리고 c동일합니다. +수술 과 다른 이유는 무엇 입니까?


"이유"를 설명하려면 :

+작업 은 원래 배열에 배열 요소를 추가합니다 . array.append작업은 배열 (또는 임의의 객체)을 원래 배열의 끝에 삽입하여 해당 지점에서 self대한 참조를 생성 합니다 (따라서 무한 재귀).

여기서 차이점은 + 연산 은 요소를 연결하여 배열을 추가 할 때 특정 적으로 작동한다는 것입니다 (다른 것처럼 오버로드 됨, 시퀀스에 대한 이 장 참조 ). 그러나 append-method는 문자 그대로 사용자가 요청하는 작업을 수행합니다. 요소를 가져 오는 대신 사용자가 제공 한 오른쪽 (배열 또는 다른 개체)에 개체를 추가합니다.

대안

extend()+ 연산자와 유사한 역할을하는 함수를 사용하려는 경우 사용 합니다 (다른 사용자도 여기에 표시됨). 반대의 경우는 현명하지 않습니다. 목록에 대해 + 연산자를 사용하여 추가를 모방 하는 것입니다 (이유에 대한 이전 링크 참조 ).

작은 역사

재미로, 약간의 역사 : 1993 년 2 월 에 파이썬 에서 배열 모듈탄생 한 것입니다 . 놀랄지도 모르지만 배열은 시퀀스와 목록이 생겨난 후에 추가되었습니다.


연결 연산자 +는 목록에 적용될 때 두 피연산자의 모든 요소를 ​​포함하는 새 목록을 반환하는 이진 중위 연산자입니다. list.append()방법은이다 mutatorlist자사의 단일 추가 object(특정 예 목록에 인수를 c피사체) list. 귀하의 예에서 이것은 c자체에 대한 참조를 추가합니다 (따라서 무한 재귀).

'+'연결의 대안

list.extend()메서드는 sequence인수를 subject와 연결하는 mutator 메서드이기도합니다 list. 특히 sequence반복 순서로 의 각 요소를 추가합니다 .

제쳐두고

연산자이기 때문에 +표현식의 결과를 새 값으로 반환합니다. 비체 인 mutator메서드 이기 때문에 list.extend()주제 목록을 제자리에서 수정하고 아무것도 반환하지 않습니다.

배열

위의 Abel의 답변이 목록, 시퀀스 및 배열에 대한 토론을 혼합하여 야기 할 수있는 잠재적 혼란 때문에 이것을 추가했습니다. Arrays정수 데이터 유형의 배열을 저장하는보다 효율적인 방법으로 시퀀스 및 목록 뒤에 Python에 추가되었습니다. arrays혼동하지 마십시오 lists. 그들은 동일하지 않습니다.

로부터 배열 문서 :

배열은 시퀀스 유형이며 목록에 저장된 객체 유형이 제한된다는 점을 제외하면 목록과 매우 유사하게 작동합니다. 유형은 단일 문자 인 유형 코드를 사용하여 객체 생성시 지정됩니다.


append목록에 요소를 추가하고 있습니다. 새 목록으로 목록을 확장하려면을 사용해야 extend합니다.

>>> c = [1, 2, 3]
>>> c.extend(c)
>>> c
[1, 2, 3, 1, 2, 3]

Python 목록은 이기종이며 동일한 목록의 요소는 모든 유형의 객체가 될 수 있습니다. 표현식 : 목록에 무엇이든지 c.append(c)객체를 추가 c합니다. 이 경우 목록 자체를 목록의 구성원으로 만듭니다.

The expression c += c adds two lists together and assigns the result to the variable c. The overloaded + operator is defined on lists to create a new list whose contents are the elements in the first list and the elements in the second list.

So these are really just different expressions used to do different things by design.


The method you're looking for is extend(). From the Python documentation:

list.append(x)
    Add an item to the end of the list; equivalent to a[len(a):] = [x].

list.extend(L)
    Extend the list by appending all the items in the given list; equivalent to a[len(a):] = L.

list.insert(i, x)
    Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).

you should use extend()

>>> c=[1,2,3]
>>> c.extend(c)
>>> c
[1, 2, 3, 1, 2, 3]

other info: append vs. extend


See the documentation:

list.append(x)

  • Add an item to the end of the list; equivalent to a[len(a):] = [x].

list.extend(L) - Extend the list by appending all the items in the given list; equivalent to a[len(a):] = L.

c.append(c) "appends" c to itself as an element. Since a list is a reference type, this creates a recursive data structure.

c += c is equivalent to extend(c), which appends the elements of c to c.

참고URL : https://stackoverflow.com/questions/2022031/python-append-vs-operator-on-lists-why-do-these-give-different-results

반응형