티스토리 뷰

반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

Getting a map() to return a list in Python 3.x

Python 3.x에서 map() 함수를 사용하여 리스트를 반환하는 방법

 문제 내용 

I'm trying to map a list into hex, and then use the list elsewhere. In python 2.6, this was easy:

저는 파이썬 3.x를 사용하여 리스트를 16진수로 매핑하고 해당 리스트를 다른 곳에서 사용하려고 합니다. 파이썬 2.6에서는 이것이 쉬웠는데요.

 

A: Python 2.6:

>>> map(chr, [66, 53, 0, 94]) ['B', '5', '\x00', '^'] 

 

However, in Python 3.1, the above returns a map object.

하지만 Python 3.1에서는 위의 코드가 맵 객체를 반환합니다.

 

B: Python 3.1:

>>> map(chr, [66, 53, 0, 94]) <map object at 0x00AF5570> 

 

How do I retrieve the mapped list (as in A above) on Python 3.x?

Python 3.x에서 매핑된 리스트(위의 A에서와 같이)를 어떻게 검색합니까?

 

Alternatively, is there a better way of doing this? My initial list object has around 45 items and id like to convert them to hex.

또 다른 방법이 있을까요? 초기 리스트 객체는 약 45개의 항목이 있으며 16진수로 변환하려고 합니다.

 

 

 

 높은 점수를 받은 Solution 

Do this:

이렇게 하세요:
list(map(chr,[66,53,0,94])) 

 

In Python 3+, many processes that iterate over iterables return iterators themselves. In most cases, this ends up saving memory, and should make things go faster.

Python 3 이상에서는 iterable을 반복하는 많은 프로세스가 스스로 이터레이터를 반환합니다. 대개의 경우 이것은 메모리를 절약하고 작업을 더 빠르게 수행할 수 있게 만들어줍니다.

 

If all you're going to do is iterate over this list eventually, there's no need to even convert it to a list, because you can still iterate over the map object like so:

만약에 이 리스트를 반복해서 사용한다면, 실제 리스트로 변환할 필요가 없습니다. 왜냐하면, 이터레이터 객체로써, map 오브젝트를 반복해서 사용할 수 있기 때문입니다. 따라서 아래와 같이 작성할 수 있습니다:
# Prints "ABCD" for ch in map(chr,[65,66,67,68]):     print(ch) 

 

 

 가장 최근 달린 Solution 

Converting my old comment for better visibility: For a "better way to do this" without map entirely, if your inputs are known to be ASCII ordinals, it's generally much faster to convert to bytes and decode, a la bytes(list_of_ordinals).decode('ascii'). That gets you a str of the values, but if you need a list for mutability or the like, you can just convert it (and it's still faster).

For example, in ipython microbenchmarks converting 45 inputs:

"map를 사용하지 않은 더 나은 방법"에 대한 이전 댓글을 보다 쉽게 볼 수 있도록 전환합니다. 입력 값이 ASCII 서수임이 알려져 있다면, 많은 경우 바이트로 변환하고 디코딩하는 것이 일반적으로 훨씬 빠릅니다. `bytes(list_of_ordinals).decode('ascii')`와 같이 작성하면 해당 값의 문자열이 반환됩니다. 그러나 가변성 또는 유사한 이유로 리스트가 필요한 경우, 값을 변환하기만 하면 됩니다(그리고 여전히 더 빠릅니다).

예를 들어, ipython 마이크로 벤치 마크에서 45개의 입력을 변환하는 경우: 
>>> %%timeit -r5 ordinals = list(range(45)) ... list(map(chr, ordinals)) ... 3.91 µs ± 60.2 ns per loop (mean ± std. dev. of 5 runs, 100000 loops each)  >>> %%timeit -r5 ordinals = list(range(45)) ... [*map(chr, ordinals)] ... 3.84 µs ± 219 ns per loop (mean ± std. dev. of 5 runs, 100000 loops each)  >>> %%timeit -r5 ordinals = list(range(45)) ... [*bytes(ordinals).decode('ascii')] ... 1.43 µs ± 49.7 ns per loop (mean ± std. dev. of 5 runs, 1000000 loops each)  >>> %%timeit -r5 ordinals = list(range(45)) ... bytes(ordinals).decode('ascii') ... 781 ns ± 15.9 ns per loop (mean ± std. dev. of 5 runs, 1000000 loops each) 

 

If you leave it as a str, it takes ~20% of the time of the fastest map solutions; even converting back to list it's still less than 40% of the fastest map solution. Bulk convert via bytes and bytes.decode then bulk converting back to list saves a lot of work, but as noted, only works if all your inputs are ASCII ordinals (or ordinals in some one byte per character locale specific encoding, e.g. latin-1).

만약 ASCII ordinal이라는 것이 보장된다면, map을 사용하지 않고 문자열을 bytes로 변환한 뒤 다시 디코딩하는 것이 훨씬 빠릅니다. `bytes(list_of_ordinals).decode('ascii')` 형태로 변환하여 문자열로 값을 반환합니다. 만약 변경 가능성이나 기타 이유로 리스트가 필요하다면, 이를 다시 변환할 수 있으며 이 경우에도 여전히 더 빠릅니다. 이를 Ipython에서 45개의 입력을 변환하는 마이크로벤치마크에서 검증한 결과, map을 사용하는 것보다 20% 이하의 시간이 소요됩니다. 이 방법을 사용할 때는 ASCII ordinal이나 1바이트 당 1개 문자인 로캘 지정 인코딩 (예: latin-1)으로 인코딩된 입력만 사용할 수 있다는 점에 유의해야 합니다.

 

 

 

출처 : https://stackoverflow.com/questions/1303347/getting-a-map-to-return-a-list-in-python-3-x

반응형
댓글
공지사항
최근에 올라온 글