如何用python填充0
我想从另一个列表中获得一个固定长度的列表,如:
a = ['a','b','c'] b = [0,0,0,0,0,0,0,0,0,0]
我想得到这样的列表: ['a','b','c',0,0,0,0,0,0,0]
。 换句话说,如果len(a) < len(b)
,我想用列表b
值填充列表a
,直到列表b
长度,有点类似于str.ljust
所做的。
这是我的代码:
a=['a','b','c'] b = [0 for i in range(5)] b = [a[i] for i in b if a[i] else i] print a
但它显示错误:
File "c.py", line 7 b = [a[i] for i in b if a[i] else i] ^ SyntaxError: invalid syntax
我能做什么?
为什么不只是:
a = a + [0]*(maxLen - len(a))
使用itertools重复。
>>> from itertools import repeat >>> a + list(repeat(0, 6)) ['a', 'b', 'c', 0, 0, 0, 0, 0, 0]
为什么不只是
c = (a + b)[:len(b)]
你不能只是做:
a = ['a','b','c'] b = [0,0,0,0,0,0,0,0] c = a + b #= ['a','b','c',0,0,0,0,0,0,0]
a+[0]*(len(b) - len(a)) ['a', 'b', 'c', 0, 0, 0, 0, 0, 0, 0]
如果你想填充可变值,例如用dict
s:
map(lambda x: {}, [None] * n)
其中n
是数组中元素的数量。
>>> map(lambda x: {}, [None] * 14) [{}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}] >>> l = map(lambda x: {}, [None] * 14) >>> l[0] {} >>> l[0]['bar'] = 'foo' >>> l [{'bar': 'foo'}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}]
填充没有lambda
会导致每个元素是{'bar': 'foo'}
!
为了更加明确,这个解决scheme将b
的所有元素replace为b
的第一个元素,而不pipea
或b
中的值如何:
a + b[len(a):]
这也将与:
>>> a = ['a', ['b'], None, False] >>> b = [0, 1, 2, 3, 4, 5] >>> a + b[len(a):] ['a', ['b'], None, False, 4, 5]
如果你不想要的结果比b
:
>>> a = ['a', ['b'], None, False] >>> b = [0, 1, 2] >>> (a + b[len(a):])[:len(b)] ['a', ['b'], None]
LIST_LENGTH = 10 a = ['a','b','c'] while len(a) < LIST_LENGTH: a.append(0)
另一个解决scheme:
a = ['a', 'b', 'c'] maxlen = 10 result = [(0 if i+1 > len(a) else a[i]) for i in range(maxlen)]
我更喜欢其他一些解决scheme。