developer tip

하나를 수정하지 않고 Python에서 두 목록을 연결하는 방법은 무엇입니까?

copycodes 2020. 10. 2. 22:49
반응형

하나를 수정하지 않고 Python에서 두 목록을 연결하는 방법은 무엇입니까? [복제]


이 질문에 이미 답변이 있습니다.

Python에서 두 목록을 연결하는 유일한 방법 list.extend은 첫 번째 목록을 수정하는입니다. 인수를 수정하지 않고 결과를 반환하는 연결 함수가 있습니까?


예 : list1+list2. 이것은 list1의 연결 인 새 목록을 제공합니다 list2.


생성 된 후 사용할 방법에 따라 itertools.chain가장 좋은 방법이 될 수 있습니다.

>>> import itertools
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = itertools.chain(a, b)

이렇게하면 결합 된 목록의 항목에 대한 생성기가 생성되어 새 목록을 만들 필요가 없다는 이점이 있지만 c두 목록을 연결 한 것처럼 계속 사용할 수 있습니다 .

>>> for i in c:
...     print i
1
2
3
4
5
6

목록이 크고 효율성이 문제라면이 방법과 itertools모듈의 다른 방법 을 알아두면 매우 편리합니다.

이 예제는의 항목을 모두 사용 c하므로 재사용하기 전에 다시 초기화해야합니다. 물론 list(c)전체 목록을 만드는 데 사용할 수 있지만 메모리에 새 목록이 만들어집니다.


concatenated_list = list_1 + list_2


인수 sum를 주면을 사용할 수도 있습니다 start.

>>> list1, list2, list3 = [1,2,3], ['a','b','c'], [7,8,9]
>>> all_lists = sum([list1, list2, list3], [])
>>> all_lists
[1, 2, 3, 'a', 'b', 'c', 7, 8, 9]

이것은 일반적으로 +연산자 가있는 모든 것에 대해 작동합니다.

>>> sum([(1,2), (1,), ()], ())
(1, 2, 1)

>>> sum([Counter('123'), Counter('234'), Counter('345')], Counter())
Counter({'1':1, '2':2, '3':3, '4':2, '5':1})

>>> sum([True, True, False], False)
2

주목할만한 문자열 예외는 다음과 같습니다.

>>> sum(['123', '345', '567'], '')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sum() can't sum strings [use ''.join(seq) instead]

you could always create a new list which is a result of adding two lists.

>>> k = [1,2,3] + [4,7,9]
>>> k
[1, 2, 3, 4, 7, 9]

Lists are mutable sequences so I guess it makes sense to modify the original lists by extend or append.


And if you have more than two lists to concatenate:

import operator
list1, list2, list3 = [1,2,3], ['a','b','c'], [7,8,9]
reduce(operator.add, [list1, list2, list3])

# or with an existing list
all_lists = [list1, list2, list3]
reduce(operator.add, all_lists)

It doesn't actually save you any time (intermediate lists are still created) but nice if you have a variable number of lists to flatten, e.g., *args.


Just to let you know:

When you write list1 + list2, you are calling the __add__ method of list1, which returns a new list. in this way you can also deal with myobject + list1 by adding the __add__ method to your personal class.

참고URL : https://stackoverflow.com/questions/4344017/how-can-i-get-the-concatenation-of-two-lists-in-python-without-modifying-either

반응형