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
진화의 한 부분이다.
원ra 파이.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() 사이에 해당하는 차이가 있는지'
이것이 도움이 될 수 있다(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()
사전 편찬자를 반환하다
목록으로 d.items()를 슬라이스할 수 있음:
>>> 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
반복기로 d.iteritems()는 슬라이스가 가능하지 않음:
>>> 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!
그래서 물건 자체는 똑같다. 물건을 배달하는 컨테이너는 다르다.하나는 목록이고, 다른 하나는 반복기(Python 버전에 따라...)
따라서 drc.items()와 drc.iteritems() 사이의 적용 가능한 차이는 목록과 반복자 사이의 적용 가능한 차이와 동일하다.
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
내 컴퓨터의 출력:
Time with d.items(): 9.04773592949
Time with d.iteritems(): 2.17707300186
이것은 분명히 을 보여준다.dictionary.iteritems()
훨씬 더 효율적이다.
dict.iteritems
Python3.x에서는 없어졌으므로 사용iter(dict.items())
동일한 출력 및 메모리 위치를 얻으려면
있다면
dict = {key1:value1, key2:value2, key3:value3,...}
파이톤 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())
튜플은 똑같다.너는 튜플을 서로 비교해서 똑같아졌어.
dict = {i: i * 2 for i in xrange(10000000)}
# More memory efficient.
for key, value in dict.iteritems():
print(key,":",value)
파이톤 3에서는dict.items()
더 이상 drc.iteritems는 제거되므로 이다.
Python 2와 3 모두에서 작동하는 사전의 항목 쌍을 반복하는 방법을 원한다면 다음과 같은 방법을 시도해 보십시오.
DICT_ITER_ITEMS = (lambda d: d.iteritems()) if hasattr(dict, 'iteritems') else (lambda d: iter(d.items()))
다음과 같이 사용하십시오.
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')
python 2의 detc.iteritemss는 python 3의 detc.discript와 같다.
'programing' 카테고리의 다른 글
Python에서 pathlib가 있는 파일 복사 (0) | 2022.04.08 |
---|---|
(Vue) 비동기/대기 모드를 사용한 RouteUpdate 전? (0) | 2022.04.08 |
ReactNative 앱에서 EXPO_DEBUG 값을 설정하는 위치? (0) | 2022.04.08 |
Vue.js에게 강제로 재장전/재장전할 수 있는가? (0) | 2022.04.08 |
Rails 5.1 app with Vue and webpacker 3, css not compiled (0) | 2022.04.07 |