ProgramingTip

Python 목록에서 정렬과 uniq를 수행하는 가장 육종 방법은 무엇입니까?

bestdevel 2021. 1. 6. 20:54
반응형

Python 목록에서 정렬과 uniq를 수행하는 가장 육종 방법은 무엇입니까?


주목 목록 고려 my_list함유 ['foo', 'foo', 'bar'].

목록 uniquify 하고 정렬하는 가장 Pythonic 방법은 무엇입니까?
(생각하다 cat my_list | sort | uniq)

이것이 내가 현재하는 방법이 확실합니다.

my_list = []
...
my_list.append("foo")
my_list.append("foo")
my_list.append("bar")
...
my_list = set(my_list)
my_list = list(my_list)
my_list.sort()

my_list = sorted(set(my_list))

# Python ≥ 2.4
# because of (generator expression) and itertools.groupby, sorted

import itertools

def sort_uniq(sequence):
    return (x[0] for x in itertools.groupby(sorted(sequence)))

더 빠름 :

import itertools, operator
import sys

if sys.hexversion < 0x03000000:
    mapper= itertools.imap # 2.4 ≤ Python < 3
else:
    mapper= map # Python ≥ 3

def sort_uniq(sequence):
    return mapper(
        operator.itemgetter(0),
        itertools.groupby(sorted(sequence)))

두 가지 모두 버전 생성기를 제공 할 수 있습니다.

sequence= list(sort_uniq(sequence))

이것은 작동합니다.

>>> list(sort_uniq([[0],[1],[0]]))
[[0], [1]]

Ignacio는 간단한 솔루션을 제공합니다 sorted(set(foo)).

고유 한 데이터가있는 경우 원하는 작업이 아니라 sorted(set(...))항상 집합을 저장하고 모든 것이있는 버전의 값을 가져올 기회가 있습니다 . (그 시점에서 사람들이 종종 데이터베이스를 사용하는 것과 같은 소리를 내기 시작합니다.)

정렬 된 목록이 등록 된 멤버십을 확인하고 최악의 경우 선형 시간 항목을 추가 할 항목 bisect 사용할 수 있습니다 .

이 조건을 항상 유지하고 작업을 단순화하거나 일부 작업이 더 잘 수행 할 수행을 고려할 수 있습니다 .blist.sortedset


다른 사람들은 분류 (set (my_list))를 사용하고 있는데, 여기에 계시고, 숫자 및 튜플과 같은 해시 가능한 값에 대해 작동하지만 목록과 같은 해시 불가능한 작동하지 않습니다.

중복없이 정렬 가능한 유형의 정렬 된 값 목록을 가져 오려면 다음을 수행하십시오.

from itertools import izip, islice
def unique_sorted(values):
    "Return a sorted list of the given values, without duplicates."
    values = sorted(values)
    if not values:
        return []
    consecutive_pairs = izip(values, islice(values, 1, len(values)))
    result = [a for (a, b) in consecutive_pairs if a != b]
    result.append(values[-1])
    return result

itertools 문서 에서 "pairwise"또는 "unique_justseen"레시피를 사용하여 더 단순화 할 수 있습니다 .


그렇게하는 것이 깨끗한 방법이라고 말할 수는 없지만 재미를 위해 :

my_list = [x for x in sorted(my_list) if not x in locals()["_[1]"]]

참조 URL : https://stackoverflow.com/questions/2931672/what-is-the-cleanest-way-to-do-a-sort-plus-uniq-on-a-python-list

반응형