python2에서 drit.items()와 drit.iteritems()의 차이점은 무엇인가?
와 사이에 적용 가능한 차이점이 있는가?
dict.items()
: 사전의 (키, 값) 쌍 목록 사본을 반환한다.
dict.iteritems()
: 사전의 (키, 값) 쌍을 통해 반복기를 반환하십시오.
아래 코드를 실행하면 각각 동일한 객체에 대한 참조를 반환하는 것 같다.내가 놓치고 있는 미묘한 차이점이 있는가?
#!/usr/bin/python
d={1:'one',2:'two',3:'three'}
print 'd.items():'
for k,v in d.items():
if d[k] is v: print '\tthey are the same object'
else: print '\tthey are different'
print 'd.iteritems():'
for k,v in d.iteritems():
if d[k] is v: print '\tthey are the same object'
else: print '\tthey are different'
출력:
d.items():
they are the same object
they are the same object
they are the same object
d.iteritems():
they are the same object
they are the same object
they are the same object
진화의 한 부분이다.
원래 파이톤items()
진짜 튜플 리스트를 만들어서 돌려줬어그것은 잠재적으로 많은 추가 메모리를 필요로 할 수 있다.
그 후, 일반적으로 발전기가 언어에 도입되었고, 그 방법은 이름이 붙여진 반복기-발생기 방법으로 재구현되었다.iteritems()
원본은 역호환성을 위해 남아있다.
Python 3의 변화 중 하나는items()
이제 보기를 반환하고list
완전히 지어진 적이 없다.그iteritems()
그 이후로 방법 또한 없어졌다.items()
Python 3에서는 다음과 같은 작업을 한다.viewitems()
파이톤 2.7에서.
dict.items()
2-tule 목록을 반환한다([(key, value), (key, value), ...]
), 반면dict.iteritems()
2-touple을 생성하는 발전기 입니다.전자는 초기에는 더 많은 공간과 시간이 걸리지만, 각 요소에 접근하는 것은 빠른 반면, 두 번째는 초기에는 더 적은 공간과 시간이 걸리지만, 각 원소를 생성하는 데는 조금 더 많은 시간이 걸린다.
Py2.x에서
명령어dict.items()
,dict.keys()
그리고dict.values()
사전의 목록 사본을 돌려주다(k, v)
페어, 키 및 값.복사된 목록이 매우 크면 많은 메모리가 필요할 수 있다.
명령어dict.iteritems()
,dict.iterkeys()
그리고dict.itervalues()
사전의 반복자를 돌려주다.(k, v)
페어, 키 및 값.
명령어dict.viewitems()
,dict.viewkeys()
그리고dict.viewvalues()
사전의 변경사항을 반영할 수 있는 보기 객체를 반환한다(즉, 다음 경우에 해당).del
한 가지 항목 또는 추가(k,v)
사전에서 보기 객체는 동시에 자동으로 변경될 수 있다.)
$ python2.7
>>> d = {'one':1, 'two':2}
>>> type(d.items())
<type 'list'>
>>> type(d.keys())
<type 'list'>
>>>
>>>
>>> type(d.iteritems())
<type 'dictionary-itemiterator'>
>>> type(d.iterkeys())
<type 'dictionary-keyiterator'>
>>>
>>>
>>> type(d.viewitems())
<type 'dict_items'>
>>> type(d.viewkeys())
<type 'dict_keys'>
Py3에 있는 동안.x
Py3.x에서는, 사물이 단지 있기 때문에, 더 깨끗하다.dict.items()
,dict.keys()
그리고dict.values()
사용 가능한, 다음과 같이 뷰 객체를 반환함dict.viewitems()
Py2.x에서.
그렇지만
@lvc에서 지적했듯이 뷰 객체는 반복기와 같지 않으므로 Py3.x에서 반복기를 반환하려면 다음을 사용하십시오.
$ python3.3
>>> d = {'one':'1', 'two':'2'}
>>> type(d.items())
<class 'dict_items'>
>>>
>>> type(d.keys())
<class 'dict_keys'>
>>>
>>>
>>> ii = iter(d.items())
>>> type(ii)
<class 'dict_itemiterator'>
>>>
>>> ik = iter(d.keys())
>>> type(ik)
<class 'dict_keyiterator'>
질문하셨습니다: 'drit.items()와 drit.iteritems() 사이에 해당하는 차이가 있는지'
This may help (for Python 2.x):
>>> d={1:'one',2:'two',3:'three'}
>>> type(d.items())
<type 'list'>
>>> type(d.iteritems())
<type 'dictionary-itemiterator'>
알 수 있다.d.items()
키의 튜플 목록, 값 쌍 및d.iteritems()
사전 편찬자를 반환하다
As a list, d.items() is slice-able:
>>> l1=d.items()[0]
>>> l1
(1, 'one') # an unordered value!
그러나 그런 일은 없을 것이다.__iter__
방법:
>>> next(d.items())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list object is not an iterator
As an iterator, d.iteritems() is not slice-able:
>>> i1=d.iteritems()[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'dictionary-itemiterator' object is not subscriptable
하지만 있다.__iter__
:
>>> next(d.iteritems())
(1, 'one') # an unordered value!
So the items themselves are same -- the container delivering the items are different. One is a list, the other an iterator (depending on the Python version...)
So the applicable differences between dict.items() and dict.iteritems() are the same as the applicable differences between a list and an iterator.
dict.items()
튜플 목록 반환dict.iteritems()
사전에서 tuple의 반복자 개체를 다음과 같이 반환하다.(key,value)
. 튜플은 같지만 용기는 다르다.
dict.items()
기본적으로 모든 사전을 목록으로 복사한다.다음 코드를 사용하여 의 실행 시간을 비교하십시오.dict.items()
그리고dict.iteritems()
차이점을 보게 될 것이다.
import timeit
d = {i:i*2 for i in xrange(10000000)}
start = timeit.default_timer() #more memory intensive
for key,value in d.items():
tmp = key + value #do something like print
t1 = timeit.default_timer() - start
start = timeit.default_timer()
for key,value in d.iteritems(): #less memory intensive
tmp = key + value
t2 = timeit.default_timer() - start
Output in my machine:
Time with d.items(): 9.04773592949
Time with d.iteritems(): 2.17707300186
이것은 분명히 을 보여준다.dictionary.iteritems()
훨씬 더 효율적이다.
dict.iteritems
Python3.x에서는 없어졌으므로 사용iter(dict.items())
동일한 출력 및 메모리 위치를 얻으려면
If you have
dict = {key1:value1, key2:value2, key3:value3,...}
In Python 2, dict.items()
각 튜플을 복사하고 사전의 튜플 목록을 반환한다. [(key1,value1), (key2,value2), ...]
. 전체 사전이 튜플을 포함하는 새 목록에 복사된다는 의미
dict = {i: i * 2 for i in xrange(10000000)}
# Slow and memory hungry.
for key, value in dict.items():
print(key,":",value)
dict.iteritems()
사전 항목 반복기를 반환한다.반품된 품목의 가치도 동일하다. (key1,value1), (key2,value2), ...
그러나 이것은 목록이 아니다.이것은 단지 사전 항목 반복자 객체일 뿐이다.즉 메모리 사용량이 줄어든다(50% 감소).
- 변경 가능한 스냅샷으로 나열:
d.items() -> list(d.items())
- 반복기 개체:
d.iteritems() -> iter(d.items())
The tuples are the same. You compared tuples in each so you get same.
dict = {i: i * 2 for i in xrange(10000000)}
# More memory efficient.
for key, value in dict.iteritems():
print(key,":",value)
In Python 3, dict.items()
returns objects.drc.iteritems()는 제거되므로 더 이상 문제가 없다.
If you want a way to iterate the item pairs of a dictionary that works with both Python 2 and 3, try something like this:
DICT_ITER_ITEMS = (lambda d: d.iteritems()) if hasattr(dict, 'iteritems') else (lambda d: iter(d.items()))
Use it like this:
for key, value in DICT_ITER_ITEMS(myDict):
# Do something with 'key' and/or 'value'.
dict.iteritems()
: 반복기를 준다.반복기는 루프 외부의 다른 패턴에 사용할 수 있다.
student = {"name": "Daniel", "student_id": 2222}
for key,value in student.items():
print(key,value)
('student_id', 2222)
('name', 'Daniel')
for key,value in student.iteritems():
print(key,value)
('student_id', 2222)
('name', 'Daniel')
studentIterator = student.iteritems()
print(studentIterator.next())
('student_id', 2222)
print(studentIterator.next())
('name', 'Daniel')
dict.iteritems() in python 2 is equivalent to dict.items() in python 3.
ReferenceURL : https://stackoverflow.com/questions/10458437/what-is-the-difference-between-dict-items-and-dict-iteritems-in-python2
'Programing' 카테고리의 다른 글
Vue: 이미 정의된 슬롯 무시 슬롯 래퍼 (0) | 2022.04.04 |
---|---|
React 애플리케이션에서 사용자를 리디렉션하는 모범 사례는 무엇인가? (0) | 2022.04.04 |
Python에서 어떻게 시간 지연을 할 수 있을까? (0) | 2022.04.04 |
http.post에서 응답을 기다리는 동안 어떻게 취소하는가? (0) | 2022.04.04 |
RxJs 5 공유() 운영자는 어떻게 작동하나? (0) | 2022.04.03 |