programing

컬렉션의 항목에 액세스합니다.인덱스별 정렬 딕트

telebox 2023. 5. 7. 11:22
반응형

컬렉션의 항목에 액세스합니다.인덱스별 정렬 딕트

다음 코드가 있다고 가정해 보겠습니다.

import collections
d = collections.OrderedDict()
d['foo'] = 'python'
d['bar'] = 'spam'

다음과 같이 번호가 매겨진 방식으로 항목에 액세스할 수 있는 방법이 있습니까?

d(0) #foo's Output
d(1) #bar's Output

만약 그것이OrderedDict()(과 같이 할 수 .

>>> import collections
>>> d = collections.OrderedDict()
>>> d['foo'] = 'python'
>>> d['bar'] = 'spam'
>>> d.items()
[('foo', 'python'), ('bar', 'spam')]
>>> d.items()[0]
('foo', 'python')
>>> d.items()[1]
('bar', 'spam')

Python 3에 대한 참고 사항.x

dict.items목록이 아닌 반복 가능한 딕트 뷰 개체를 반환합니다.색인화를 가능하게 하려면 통화를 목록에 묶어야 합니다.

>>> items = list(d.items())
>>> items
[('foo', 'python'), ('bar', 'spam')]
>>> items[0]
('foo', 'python')
>>> items[1]
('bar', 'spam')

OrderedDict를 사용해야 합니까? 아니면 빠른 위치 인덱싱을 통해 어떤 식으로든 정렬된 맵과 유사한 유형을 사용하시겠습니까?후자의 경우 Python의 여러 정렬된 딕트 유형 중 하나(키 정렬 순서에 따라 키-값 쌍을 정렬함)를 고려합니다.일부 구현에서는 빠른 인덱싱도 지원합니다.예를 들어 정렬된 컨테이너 프로젝트에는 이 용도로만 SortedDict 유형이 있습니다.

>>> from sortedcontainers import SortedDict
>>> sd = SortedDict()
>>> sd['foo'] = 'python'
>>> sd['bar'] = 'spam'
>>> print sd.iloc[0] # Note that 'bar' comes before 'foo' in sort order.
'bar'
>>> # If you want the value, then simple do a key lookup:
>>> print sd[sd.iloc[1]]
'python'

목록을 만들지 않고 OrderedDict의 첫 번째 항목(또는 그에 가까운 항목)을 원하는 경우 다음과 같은 특별한 경우가 있습니다.(이것은 Python 3으로 업데이트되었습니다):

>>> from collections import OrderedDict
>>> 
>>> d = OrderedDict()
>>> d["foo"] = "one"
>>> d["bar"] = "two"
>>> d["baz"] = "three"
>>> next(iter(d.items()))
('foo', 'one')
>>> next(iter(d.values()))
'one'

(처음 "다음()"이라고 말할 때, 그것은 정말로 "첫 번째"를 의미합니다.")

에서, 식테서에트스비공서.next(iter(d.items()))는 OrderedDict보다 더 .items()[0]의 OrderDict를 경우 10 항목이 포함됩니다.next(iter(d.items()))은 배다약 200더다보다 약 더 빨랐습니다.items()[0].

그러나 항목() 목록을 한 번 저장한 다음 목록을 많이 사용하면 더 빠를 수 있습니다.또는 {항목() 반복기를 반복적으로 생성하여 원하는 위치로 이동하는 경우 속도가 느려질 수 있습니다.

패키지에서 IndexedOrderDict를 사용하는 것이 훨씬 효율적입니다.

Niklas의 의견에 따라 OrderedDictIndexedOrdedDict에 대한 벤치마크를 1000개 항목으로 수행했습니다.

In [1]: from numpy import *
In [2]: from indexed import IndexedOrderedDict
In [3]: id=IndexedOrderedDict(zip(arange(1000),random.random(1000)))
In [4]: timeit id.keys()[56]
1000000 loops, best of 3: 969 ns per loop

In [8]: from collections import OrderedDict
In [9]: od=OrderedDict(zip(arange(1000),random.random(1000)))
In [10]: timeit od.keys()[56]
10000 loops, best of 3: 104 µs per loop

IndexedOrderedDict는 이 특정한 경우 특정 위치에 있는 요소를 인덱싱하는 속도가 최대 100배 빠릅니다.

나열된 다른 솔루션에는 추가 단계가 필요합니다. IndexedOrderedDict는 의대입다니의 입니다.OrderedDict색인화할 수 있다는 것만 빼면요

이 커뮤니티 위키는 기존 답변을 수집하려고 합니다.

파이썬 2.7

에서 이썬에 2서파는keys(),values(),그리고.items()OrderedDict리턴 리스트사용.values를 들어, 방법은 , 간한방법은입니다.

d.values()[0]  # "python"
d.values()[1]  # "spam"

단일 인덱스에만 관심이 있는 대규모 컬렉션의 경우 생성기 버전을 사용하여 전체 목록을 생성하지 않을 수 있습니다.iterkeys,itervalues그리고.iteritems:

import itertools
next(itertools.islice(d.itervalues(), 0, 1))  # "python"
next(itertools.islice(d.itervalues(), 1, 2))  # "spam"

인덱스.py 패키지가 제공합니다.IndexedOrderedDict이 사용 사례를 위해 설계되었으며 가장 빠른 옵션이 될 것입니다.

from indexed import IndexedOrderedDict
d = IndexedOrderedDict({'foo':'python','bar':'spam'})
d.values()[0]  # "python"
d.values()[1]  # "spam"

랜덤 액세스가 가능한 대규모 사전의 경우 iter 값을 사용하는 것이 훨씬 빠를 수 있습니다.

$ python2 -m timeit -s 'from collections import OrderedDict; from random import randint; size = 1000;   d = OrderedDict({i:i for i in range(size)})'  'i = randint(0, size-1); d.values()[i:i+1]'
1000 loops, best of 3: 259 usec per loop
$ python2 -m timeit -s 'from collections import OrderedDict; from random import randint; size = 10000;  d = OrderedDict({i:i for i in range(size)})' 'i = randint(0, size-1); d.values()[i:i+1]'
100 loops, best of 3: 2.3 msec per loop
$ python2 -m timeit -s 'from collections import OrderedDict; from random import randint; size = 100000; d = OrderedDict({i:i for i in range(size)})' 'i = randint(0, size-1); d.values()[i:i+1]'
10 loops, best of 3: 24.5 msec per loop

$ python2 -m timeit -s 'from collections import OrderedDict; from random import randint; size = 1000;   d = OrderedDict({i:i for i in range(size)})' 'i = randint(0, size-1); next(itertools.islice(d.itervalues(), i, i+1))'
10000 loops, best of 3: 118 usec per loop
$ python2 -m timeit -s 'from collections import OrderedDict; from random import randint; size = 10000;  d = OrderedDict({i:i for i in range(size)})' 'i = randint(0, size-1); next(itertools.islice(d.itervalues(), i, i+1))'
1000 loops, best of 3: 1.26 msec per loop
$ python2 -m timeit -s 'from collections import OrderedDict; from random import randint; size = 100000; d = OrderedDict({i:i for i in range(size)})' 'i = randint(0, size-1); next(itertools.islice(d.itervalues(), i, i+1))'
100 loops, best of 3: 10.9 msec per loop

$ python2 -m timeit -s 'from indexed import IndexedOrderedDict; from random import randint; size = 1000;   d = IndexedOrderedDict({i:i for i in range(size)})' 'i = randint(0, size-1); d.values()[i]'
100000 loops, best of 3: 2.19 usec per loop
$ python2 -m timeit -s 'from indexed import IndexedOrderedDict; from random import randint; size = 10000;  d = IndexedOrderedDict({i:i for i in range(size)})' 'i = randint(0, size-1); d.values()[i]'
100000 loops, best of 3: 2.24 usec per loop
$ python2 -m timeit -s 'from indexed import IndexedOrderedDict; from random import randint; size = 100000; d = IndexedOrderedDict({i:i for i in range(size)})' 'i = randint(0, size-1); d.values()[i]'
100000 loops, best of 3: 2.61 usec per loop

+--------+-----------+----------------+---------+
|  size  | list (ms) | generator (ms) | indexed |
+--------+-----------+----------------+---------+
|   1000 | .259      | .118           | .00219  |
|  10000 | 2.3       | 1.26           | .00224  |
| 100000 | 24.5      | 10.9           | .00261  |
+--------+-----------+----------------+---------+

파이썬 3.6

Python 3에는 동일한 두 가지 기본 옵션(list vs generator)이 있지만 dict 메서드는 기본적으로 생성자를 반환합니다.

목록 방법:

list(d.values())[0]  # "python"
list(d.values())[1]  # "spam"

제너레이터 방법:

import itertools
next(itertools.islice(d.values(), 0, 1))  # "python"
next(itertools.islice(d.values(), 1, 2))  # "spam"

Python 3 사전은 Python 2보다 몇 배 더 빠르며 제너레이터를 사용하기 위한 속도 향상이 유사합니다.

+--------+-----------+----------------+---------+
|  size  | list (ms) | generator (ms) | indexed |
+--------+-----------+----------------+---------+
|   1000 | .0316     | .0165          | .00262  |
|  10000 | .288      | .166           | .00294  |
| 100000 | 3.53      | 1.48           | .00332  |
+--------+-----------+----------------+---------+

새로운 시대이며 Python 3.6.1 사전은 이제 순서를 유지합니다.이러한 의미론은 BDFL 승인이 필요하기 때문에 명시적이지 않습니다.하지만 레이먼드 헤팅어는 차선책이고 (그리고 더 재미있는) 그는 사전이 아주 오랫동안 주문될 것이라는 꽤 강력한 주장을 합니다.

이제 사전 조각을 쉽게 만들 수 있습니다.

test_dict = {
                'first':  1,
                'second': 2,
                'third':  3,
                'fourth': 4
            }

list(test_dict.items())[:2]

참고: 사전 삽입 순서 보존은 이제 Python 3.7에서 공식화되었습니다.

가지고 계신다면,pandas설치된 경우, 당신은 주문된 딕트를 팬더로 변환할 수 있습니다.Series이렇게 하면 사전 요소에 임의로 액세스할 수 있습니다.

>>> import collections
>>> import pandas as pd
>>> d = collections.OrderedDict()
>>> d['foo'] = 'python'
>>> d['bar'] = 'spam'

>>> s = pd.Series(d)

>>> s['bar']
spam
>>> s.iloc[1]
spam
>>> s.index[1]
bar

OrderedDict()의 경우 다음과 같이 (키, 값) 쌍의 튜플을 가져오거나 '.values()'를 사용하여 요소에 액세스할 수 있습니다.

>>> import collections
>>> d = collections.OrderedDict()
>>> d['foo'] = 'python'
>>> d['bar'] = 'spam'
>>> d.items()
[('foo', 'python'), ('bar', 'spam')]
>>>d.values()
odict_values(['python','spam'])
>>>list(d.values())
['python','spam']

미리 알고 있는 고정수를 처리하는 경우 대신 Python의 내장된 명명된 튜플을 사용합니다.가능한 사용 사례는 일정한 데이터를 저장하고 인덱싱 및 키 지정을 통해 프로그램 전체에 액세스하려는 경우입니다.

import collections
ordered_keys = ['foo', 'bar']
D = collections.namedtuple('D', ordered_keys)
d = D(foo='python', bar='spam')

인덱싱을 통한 액세스:

d[0] # result: python
d[1] # result: spam

키를 지정하여 액세스:

d.foo # result: python
d.bar # result: spam

또는 그 이상:

getattr(d, 'foo') # result: python
getattr(d, 'bar') # result: spam

언급URL : https://stackoverflow.com/questions/10058140/accessing-items-in-an-collections-ordereddict-by-index

반응형