Some built-in to pad a list in python

前端 未结 10 1938
暗喜
暗喜 2020-11-27 14:06

I have a list of size < N and I want to pad it up to the size N with a value.

Certainly, I can use something like the following, but I feel that there sh

10条回答
  •  孤城傲影
    2020-11-27 14:45

    gnibbler's answer is nicer, but if you need a builtin, you could use itertools.izip_longest (zip_longest in Py3k):

    itertools.izip_longest( xrange( N ), list )
    

    which will return a list of tuples ( i, list[ i ] ) filled-in to None. If you need to get rid of the counter, do something like:

    map( itertools.itemgetter( 1 ), itertools.izip_longest( xrange( N ), list ) )
    

提交回复
热议问题