programing tip

`sorted (list)`와`list.sort ()`의 차이점은 무엇입니까?

itbloger 2020. 5. 31. 21:00
반응형

`sorted (list)`와`list.sort ()`의 차이점은 무엇입니까?


list.sort()목록을 정렬하고 정렬 된 목록을 저장하는 한편 sorted(list)원래 목록을 변경하지 않고 목록의 정렬 된 사본 반환합니다.

  • 그러나 언제 사용해야합니까?
  • 그리고 어느 것이 더 빠릅니까? 그리고 얼마나 빨리?
  • 다음에 목록의 원래 위치를 검색 할 수 있습니까 list.sort()?

sorted() 정렬 된 목록을 반환 하고 원래 목록은 영향을받지 않습니다. list.sort()리스트를 in-place 정렬하고리스트 인덱스를 변경하고 None모든 in-place 조작과 같이 리턴합니다 .

sorted()목록뿐만 아니라 반복 가능한 작업에서도 작동합니다. 문자열, 튜플, 사전 (키를 얻음), 생성기 등 모든 요소가 포함 된 목록을 정렬하여 반환합니다.

  • 정렬 된 새 객체를 원할 때 list.sort()목록을 변경하려는 경우에 사용하십시오 sorted(). 사용 sorted()당신은 반복 가능한 아닌 목록 무언가 정렬 할 때 이 아직 없습니다 .

  • 목록의 경우 사본을 만들 필요가 없으므로 list.sort()보다 빠릅니다 sorted(). 다른 iterable의 경우 선택의 여지가 없습니다.

  • 아니요, 원래 위치를 검색 할 수 없습니다. 당신 list.sort()이 원래 주문 을 호출 하면 사라집니다.


의 차이 무엇입니까 sorted(list)대는 list.sort()?

  • list.sort 현재 위치에서 목록을 변경하고 리턴 None
  • sorted iterable을 취하고 정렬 된 새 목록을 리턴합니다.

sorted 이 Python 구현과 동일하지만 CPython 내장 함수는 C로 작성 될 때 측정 속도가 훨씬 빠릅니다.

def sorted(iterable, key=None):
    new_list = list(iterable)    # make a new list
    new_list.sort(key=key)       # sort it
    return new_list              # return it

언제 사용합니까?

  • 사용 list.sort원래 정렬 순서를 유지하지 않으려는 경우 (따라서 당신은. 메모리에 현재 위치에서 목록을 다시 사용할 수있을 것입니다) 당신은 (목록의 유일한 소유자 인 경우 목록은 다른 코드와 공유하는 경우 변경하면 해당 목록이 사용되는 버그가 발생할 수 있습니다.)
  • 사용 sorted원래 정렬 순서를 유지하려는 경우 또는 당신은 당신의 지역 코드가 소유 새로운 목록을 작성하고자 할 때.

list.sort () 후에 목록의 원래 위치를 검색 할 수 있습니까?

아니요-직접 복사하지 않으면 정렬이 완료되어 해당 정보가 손실됩니다.

"그리고 어느 것이 더 빠릅니까? 그리고 얼마나 빠릅니까?"

새 목록을 만드는 데 따른 불이익을 설명하기 위해 timeit 모듈을 사용하십시오. 설정은 다음과 같습니다.

import timeit
setup = """
import random
lists = [list(range(10000)) for _ in range(1000)]  # list of lists
for l in lists:
    random.shuffle(l) # shuffle each list
shuffled_iter = iter(lists) # wrap as iterator so next() yields one at a time
"""

그리고 여기 무작위로 배열 된 10000 개의 정수 목록에 대한 결과가 있습니다. 여기에서 볼 수 있듯이, 우리는 오래된 목록 작성 비용 신화를 반증 했습니다 .

파이썬 2.7

>>> timeit.repeat("next(shuffled_iter).sort()", setup=setup, number = 1000)
[3.75168503401801, 3.7473005310166627, 3.753129180986434]
>>> timeit.repeat("sorted(next(shuffled_iter))", setup=setup, number = 1000)
[3.702025591977872, 3.709248117986135, 3.71071034099441]

파이썬 3

>>> timeit.repeat("next(shuffled_iter).sort()", setup=setup, number = 1000)
[2.797430992126465, 2.796825885772705, 2.7744789123535156]
>>> timeit.repeat("sorted(next(shuffled_iter))", setup=setup, number = 1000)
[2.675589084625244, 2.8019039630889893, 2.849375009536743]

피드백을받은 후에 다른 특성을 가진 다른 테스트가 바람직하다고 결정했습니다. 여기에서는 각 반복에 대해 길이가 100,000 배인 동일한 무작위 순서의 목록을 1,000 번 제공합니다.

import timeit
setup = """
import random
random.seed(0)
lst = list(range(100000))
random.shuffle(lst)
"""

나는 Martijn이 언급 한 복사에서 오는이 더 큰 종류의 차이점을 해석하지만, 여기에서 더 오래된 더 인기있는 답변에 언급 된 지점까지 지배하지는 않습니다. 여기서 시간의 증가는 약 10 %입니다

>>> timeit.repeat("lst[:].sort()", setup=setup, number = 10000)
[572.919036605, 573.1384446719999, 568.5923951]
>>> timeit.repeat("sorted(lst[:])", setup=setup, number = 10000)
[647.0584738299999, 653.4040515829997, 657.9457361929999]

나는 또한 훨씬 더 작은 정렬에서 위를 실행했으며 새로운 sorted사본 버전은 여전히 ​​1000 길이의 정렬에서 약 2 % 더 오래 실행되는 시간을 보았습니다 .

Poke는 자신의 코드도 실행했습니다. 코드는 다음과 같습니다.

setup = '''
import random
random.seed(12122353453462456)
lst = list(range({length}))
random.shuffle(lst)
lists = [lst[:] for _ in range({repeats})]
it = iter(lists)
'''
t1 = 'l = next(it); l.sort()'
t2 = 'l = next(it); sorted(l)'
length = 10 ** 7
repeats = 10 ** 2
print(length, repeats)
for t in t1, t2:
    print(t)
    print(timeit(t, setup=setup.format(length=length, repeats=repeats), number=repeats))

He found for 1000000 length sort, (ran 100 times) a similar result, but only about a 5% increase in time, here's the output:

10000000 100
l = next(it); l.sort()
610.5015971539542
l = next(it); sorted(l)
646.7786222379655

Conclusion:

A large sized list being sorted with sorted making a copy will likely dominate differences, but the sorting itself dominates the operation, and organizing your code around these differences would be premature optimization. I would use sorted when I need a new sorted list of the data, and I would use list.sort when I need to sort a list in-place, and let that determine my usage.


The main difference is that sorted(some_list) returns a new list:

a = [3, 2, 1]
print sorted(a) # new list
print a         # is not modified

and some_list.sort(), sorts the list in place:

a = [3, 2, 1]
print a.sort() # in place
print a         # it's modified

Note that since a.sort() doesn't return anything, print a.sort() will print None.


Can a list original positions be retrieved after list.sort()?

No, because it modifies the original list.


The .sort() function stores the value of new list directly in the list variable; so answer for your third question would be NO. Also if you do this using sorted(list), then you can get it use because it is not stored in the list variable. Also sometimes .sort() method acts as function, or say that it takes arguments in it.

You have to store the value of sorted(list) in a variable explicitly.

Also for short data processing the speed will have no difference; but for long lists; you should directly use .sort() method for fast work; but again you will face irreversible actions.


Here are a few simple examples to see the difference in action:

See the list of numbers here:

nums = [1, 9, -3, 4, 8, 5, 7, 14]

When calling sorted on this list, sorted will make a copy of the list. (Meaning your original list will remain unchanged.)

Let's see.

sorted(nums)

returns

[-3, 1, 4, 5, 7, 8, 9, 14]

Looking at the nums again

nums

We see the original list (unaltered and NOT sorted.). sorted did not change the original list

[1, 2, -3, 4, 8, 5, 7, 14]

Taking the same nums list and applying the sort function on it, will change the actual list.

Let's see.

Starting with our nums list to make sure, the content is still the same.

nums

[-3, 1, 4, 5, 7, 8, 9, 14]

nums.sort()

Now the original nums list is changed and looking at nums we see our original list has changed and is now sorted.

nums
[-3, 1, 2, 4, 5, 7, 8, 14]

Note: Simplest difference between sort() and sorted() is: sort() doesn't return any value while, sorted() returns an iterable list.

sort() doesn't return any value.

The sort() method just sorts the elements of a given list in a specific order - Ascending or Descending without returning any value.

The syntax of sort() method is:

list.sort(key=..., reverse=...)

Alternatively, you can also use Python's in-built function sorted() for the same purpose. sorted function return sorted list

 list=sorted(list, key=..., reverse=...)

참고URL : https://stackoverflow.com/questions/22442378/what-is-the-difference-between-sortedlist-vs-list-sort

반응형