Programing

목록의 특정 색인에 요소를 삽입하고 업데이트 된 목록을 반환합니다.

lottogame 2020. 11. 8. 09:10
반응형

목록의 특정 색인에 요소를 삽입하고 업데이트 된 목록을 반환합니다.


나는 이것을 가지고있다:

>>> a = [1, 2, 4]
>>> print a
[1, 2, 4]

>>> print a.insert(2, 3)
None

>>> print a
[1, 2, 3, 4]

>>> b = a.insert(3, 6)
>>> print b
None

>>> print a
[1, 2, 3, 6, 4]

어쨌든 원래 목록을 업데이트하는 대신 업데이트 된 목록을 가져올 수 있습니까?


l.insert(index, obj)실제로 아무것도 반환하지 않고 목록 만 업데이트합니다. ATO가 말했듯이 b = a[:index] + [obj] + a[index:]. 그러나 다른 방법은 다음과 같습니다.

a = [1, 2, 4]
b = a[:]
b.insert(2, 3)

가장 효율적인 성능 접근 방식

목록에서 슬라이스 인덱싱사용하여 요소를 삽입 할 수도 있습니다 . 예를 들면 :

>>> a = [1, 2, 4]
>>> insert_at = 2  # index at which you want to insert item

>>> b = a[:]   # created copy of list "a" as "b"
               # skip this step if you are ok with modifying original list

>>> b[insert_at:insert_at] = [3]  # insert "3" within "b"
>>> b
[1, 2, 3, 4]

들어 지정된 인덱스에서 함께 여러 요소를 삽입 , 당신이해야 할 모든이 (가) 사용하는 것입니다 list삽입 할 것을 여러 요소. 예를 들면 :

>>> a = [1, 2, 4]
>>> insert_at = 2   # index starting from which multiple elements will be inserted 

# List of elements that you want to insert together at "index_at" (above) position
>>> insert_elements = [3, 5, 6]

>>> a[insert_at:insert_at] = insert_elements
>>> a   # [3, 5, 6] are inserted together in `a` starting at index "2"
[1, 2, 3, 5, 6, 4]

List Comprehension을 사용하는 대안 (그러나 성능 측면에서 매우 느림) :

대안으로 목록 이해도사용하여 달성 할 수 있습니다 enumerate. (하지만 이런 식으로하지 마세요. 단지 설명을위한 것입니다) :

>>> a = [1, 2, 4]
>>> insert_at = 2

>>> b = [y for i, x in enumerate(a) for y in ((3, x) if i == insert_at else (x, ))]
>>> b
[1, 2, 3, 4]

모든 솔루션의 성능 비교

다음 timeit은 Python 3.4.5의 1000 개 요소 목록과 모든 답변을 비교 한 것입니다.

  • 슬라이스 삽입을 사용한 내 답변 -가장 빠름 (루프 당 3.08 usec)

    mquadri$ python3 -m timeit -s "a = list(range(1000))" "b = a[:]; b[500:500] = [3]"
    100000 loops, best of 3: 3.08 usec per loop
    
  • 슬라이스 목록 병합을 기반으로 한 ATOzTOA의 승인 된 답변 -초 (루프 당 6.71 usec)

    mquadri$ python3 -m timeit -s "a = list(range(1000))" "b = a[:500] + [3] + a[500:]"
    100000 loops, best of 3: 6.71 usec per loop
    
  • 가장 많이 투표 한 Rushy Panchal의 답변list.insert(...) -세 번째 (루프 당 26.5 usec)

    python3 -m timeit -s "a = list(range(1000))" "b = a[:]; b.insert(500, 3)"
    10000 loops, best of 3: 26.5 usec per loop
    
  • 내 대답 목록 이해enumerate넷째 - (매우 느린 루프 당 168 마이크로 초 포함)

    mquadri$ python3 -m timeit -s "a = list(range(1000))" "[y for i, x in enumerate(a) for y in ((3, x) if i == 500 else (x, )) ]"
    10000 loops, best of 3: 168 usec per loop
    

Shortest I got: b = a[:2] + [3] + a[2:]

>>> 
>>> a = [1, 2, 4]
>>> print a
[1, 2, 4]
>>> b = a[:2] + [3] + a[2:]
>>> print a
[1, 2, 4]
>>> print b
[1, 2, 3, 4]

Use the Python list insert() Method. Usage:

Syntax

Following is the syntax for insert() method −

list.insert(index, obj)

Parameters

  • index − This is the Index where the object obj need to be inserted.
  • obj − This is the Object to be inserted into the given list.

Return Value

This method does not return any value but it inserts the given element at the given index.

Example:

a = [1,2,4,5]

a.insert(2,3)

print(a)

Returns [1, 2, 3, 4, 5]

참고URL : https://stackoverflow.com/questions/14895599/insert-an-element-at-specific-index-in-a-list-and-return-updated-list

반응형