development

목록을 다시 정렬하려면 어떻게해야합니까?

big-blog 2020. 9. 2. 19:48
반응형

목록을 다시 정렬하려면 어떻게해야합니까?


목록이 있으면 [a,b,c,d,e]어떻게 항목을 임의의 방식으로 재정렬 할 수 [d,c,a,b,e]있습니까?

편집 : 나는 그들을 섞고 싶지 않습니다. 미리 정의 된 방식으로 다시 정렬하고 싶습니다. (예를 들어 이전 목록의 세 번째 요소가 새 목록의 첫 번째 요소가되어야한다는 것을 알고 있습니다.)


이렇게 할 수 있습니다

mylist = ['a', 'b', 'c', 'd', 'e']
myorder = [3, 2, 0, 1, 4]
mylist = [mylist[i] for i in myorder]
print(mylist)         # prints: ['d', 'c', 'a', 'b', 'e']

>>> import random
>>> x = [1,2,3,4,5]
>>> random.shuffle(x)
>>> x
[5, 2, 4, 3, 1]

>>> a = [1, 2, 3]
>>> a[0], a[2] = a[2], a[0]
>>> a
[3, 2, 1]

최종 순서는 인덱스 목록에 의해 정의됩니까?

>>> items = [1, None, "chicken", int]
>>> order = [3, 0, 1, 2]

>>> ordered_list = [items[i] for i in order]
>>> ordered_list
[<type 'int'>, 1, None, 'chicken']

편집 : meh. AJ가 더 빨랐습니다 ... 파이썬에서 목록을 어떻게 재정렬 할 수 있습니까?


>>> a=["a","b","c","d","e"]
>>> a[0],a[3] = a[3],a[0]
>>> a
['d', 'b', 'c', 'a', 'e']

사용자 고유의 정렬 기능을 제공 할 수 있습니다 list.sort().

sort () 메서드는 비교를 제어하기위한 선택적 인수를 사용합니다.

  • cmp 는 첫 번째 인수가 두 번째 인수보다 작은 지, 같은지 또는 큰지 여부에 따라 음수, 0 또는 양수를 반환해야하는 두 인수 (목록 항목)의 사용자 지정 비교 함수를 지정합니다 cmp=lambda x,y: cmp(x.lower(), y.lower()). 기본값은 None입니다.

  • key 는 각 목록 요소에서 비교 키를 추출하는 데 사용되는 하나의 인수 함수를 지정합니다 key=str.lower.. 기본값은 None입니다.

  • reverse 는 부울 값입니다. True로 설정하면 각 비교가 반전 된 것처럼 목록 요소가 정렬됩니다.

일반적으로 키 및 역변환 프로세스는 동등한 cmp 함수를 지정하는 것보다 훨씬 빠릅니다. 이는 cmp가 각 목록 요소에 대해 여러 번 호출되고 키 및 반전은 각 요소를 한 번만 터치하기 때문입니다.


numpy를 사용하는 경우 깔끔한 방법이 있습니다.

items = np.array(["a","b","c","d"])
indices = np.arange(items.shape[0])
np.random.shuffle(indices)
print(indices)
print(items[indices])

이 코드는 다음을 반환합니다.

[1 3 2 0]
['b' 'd' 'c' 'a']

효율성에 그다지 신경 쓰지 않는다면 numpy의 배열 인덱싱을 사용하여 우아하게 만들 수 있습니다.

a = ['123', 'abc', 456]
order = [2, 0, 1]
a2 = list( np.array(a, dtype=object)[order] )

귀하의 질문에 대해 이해 한 바에 따르면 .NET Framework에서 지정한 순열을 적용하려는 것으로 보입니다 list. 이것은 permuted에 나타나야 하는 원본 요소의 인덱스를 보유 하는 다른 list(그것을 호출하자 p) 지정함으로써 이루어집니다 . 그런 다음를 사용 하여 각 위치의 요소를의 해당 위치에있는 인덱스로 간단히 대체하여 새 항목을 만듭니다 .listlistplistp

def apply_permutation(lst, p):
    return [lst[x] for x in p]

arr=list("abcde")
new_order=[3,2,0,1,4]

print apply_permutation(arr,new_order)

이것은 인쇄합니다 ['d', 'c', 'a', 'b', 'e'].

이것은 실제로 새로운을 생성 list하지만 원래의 "제자리"를 영구히 변경하기 위해 사소하게 수정할 수 있습니다.


newList = [oldList[3]]
newList.extend(oldList[:3])
newList.extend(oldList[4:])

One more thing which can be considered is the other interpretation as pointed out by darkless

Code in Python 2.7

Mainly:

  1. Reorder by value - Already solved by AJ above
  2. Reorder by index

    mylist = ['a', 'b', 'c', 'd', 'e']
    myorder = [3, 2, 0, 1, 4]
    
    mylist = sorted(zip(mylist, myorder), key=lambda x: x[1])
    print [item[0] for item in mylist]
    

This will print ['c', 'd', 'b', 'a', 'e']


This is what I used when I stumbled upon this problem.

def order(list_item, i): # reorder at index i
    order_at = list_item.index(i)
    ordered_list = list_item[order_at:] + list_item[:order_at]
    return ordered_list

EX: for the the lowercase letters

order(string.ascii_lowercase, 'h'):
>>> 'hijklmnopqrstuvwxyzabcdefg'

It simply just shifts the list to a specified index

참고URL : https://stackoverflow.com/questions/2177590/how-can-i-reorder-a-list

반응형