파이썬에서 목록을 채우는 내장
크기 < N 목록이 있고 크기 N까지 값을 채우고 싶습니다.
확실히 다음과 같은 것을 사용할 수 있지만 놓친 것이 있어야한다고 생각합니다.
>>> N = 5
>>> a = [1]
>>> map(lambda x, y: y if x is None else x, a, ['']*N)
[1, '', '', '', '']
a += [''] * (N - len(a))
또는 a
자리 를 바꾸고 싶지 않은 경우
new_a = a + [''] * (N - len(a))
언제든지 목록의 하위 클래스를 만들고 원하는대로 메서드를 호출 할 수 있습니다.
class MyList(list):
def ljust(self, n, fillvalue=''):
return self + [fillvalue] * (n - len(self))
a = MyList(['1'])
b = a.ljust(5, '')
이 접근 방식은 더 시각적이고 비단뱀 적이라고 생각합니다.
a = (a + N * [''])[:N]
이를위한 내장 기능이 없습니다. 그러나 당신은 당신의 작업 (또는 무엇이든 : p)에 대한 내장을 작성할 수 있습니다.
(itertool padnone
및 take
레시피 에서 수정 됨 )
from itertools import chain, repeat, islice
def pad_infinite(iterable, padding=None):
return chain(iterable, repeat(padding))
def pad(iterable, size, padding=None):
return islice(pad_infinite(iterable, padding), size)
용법:
>>> list(pad([1,2,3], 7, ''))
[1, 2, 3, '', '', '', '']
gnibbler의 대답은 더 좋지만 내장 기능이 필요한 경우 itertools.izip_longest
( zip_longest
Py3k에서) 사용할 수 있습니다 .
itertools.izip_longest( xrange( N ), list )
( i, list[ i ] )
None으로 채워진 튜플 목록을 반환합니다 . 카운터를 제거해야하는 경우 다음과 같이하십시오.
map( itertools.itemgetter( 1 ), itertools.izip_longest( xrange( N ), list ) )
빌드 인없이 간단한 생성기를 사용할 수도 있습니다. 그러나 목록을 채우지 않고 응용 프로그램 논리가 빈 목록을 처리하도록합니다.
어쨌든 빌드가없는 반복자
def pad(iterable, padding='.', length=7):
'''
>>> iterable = [1,2,3]
>>> list(pad(iterable))
[1, 2, 3, '.', '.', '.', '.']
'''
for count, i in enumerate(iterable):
yield i
while count < length - 1:
count += 1
yield padding
if __name__ == '__main__':
import doctest
doctest.testmod()
''대신 None으로 채우려면 map ()이 작업을 수행합니다.
>>> map(None,[1,2,3],xrange(7))
[(1, 0), (2, 1), (3, 2), (None, 3), (None, 4), (None, 5), (None, 6)]
>>> zip(*map(None,[1,2,3],xrange(7)))[0]
(1, 2, 3, None, None, None, None)
more-itertools
padded
이러한 종류의 문제에 대한 특수 도구를 포함하는 라이브러리입니다 .
import more_itertools as mit
list(mit.padded(a, "", N))
# [1, '', '', '', '']
또는 @kennytm에서 언급 한대로 및 포함 more_itertools
하는 Python itertools 레시피 도 구현 하므로 다시 구현할 필요가 없습니다.padnone
take
list(mit.take(N, mit.padnone(a)))
# [1, None, None, None, None]
기본 None
패딩 을 바꾸려면 목록 이해를 사용하십시오.
["" if i is None else i for i in mit.take(N, mit.padnone(a))]
# [1, '', '', '', '']
kennytm을 종료하려면 :
def pad(l, size, padding):
return l + [padding] * abs((len(l)-size))
>>> l = [1,2,3]
>>> pad(l, 7, 0)
[1, 2, 3, 0, 0, 0, 0]
extra_length = desired_length - len(l)
l.extend(value for _ in range(extra_length))
This avoids any extra allocation, unlike any solution that depends on creating and appending the list [value] * extra_length
. The "extend" method first calls __length_hint__
on the iterator, and extends the allocation for l
by that much before filling it in from the iterator.
you can use *
iterable unpacking operator:
N = 5
a = [1]
pad_value = ''
pad_size = N - len(a)
final_list = [*a, *[pad_value] * pad_size]
print(final_list)
output:
[1, '', '', '', '']
참고URL : https://stackoverflow.com/questions/3438756/some-built-in-to-pad-a-list-in-python
'program story' 카테고리의 다른 글
ConcurrentLinkedQueue를 사용하는 방법? (0) | 2020.09.07 |
---|---|
jQuery의 이벤트 핸들러에 인수를 어떻게 전달할 수 있습니까? (0) | 2020.09.07 |
Amazon RDS 백업 / 스냅 샷은 실제로 어떻게 작동합니까? (0) | 2020.09.06 |
사진에서 종이 시트의 모서리를 감지하는 알고리즘 (0) | 2020.09.06 |
웹 서버, 웹 컨테이너 및 응용 프로그램 서버의 차이점 (0) | 2020.09.06 |