我有一个数字列表,例如:
test_list = [1,5,6,8,10]
我想用零填充此列表,以便数字仍然有序,但列表的长度为15,例如:
new_list = [1,0,0,0,5,6,0,8,0,10,0,0,0,0,0]
我该怎么做?
答案 0 :(得分:5)
您可以将列表推导与内联if / else:
结合使用[i if i in test_list else 0 for i in range(1, 16)]
答案 1 :(得分:2)
您可以将列表理解与xrange
一起使用,以检查是否包含在原始列表中。如果数字总是在1到15之间,它将如下所示:
test_list = [1,5,6,8,10]
new_list = [ x if x in test_list else 0 for x in xrange(1,16) ]
答案 2 :(得分:2)
根据这些列表可能获得的大小,您可能希望使用numpy,如果它们可以变得非常大,它会更快,并且它允许您使用另一个数组索引数组:
import numpy as np
test_list = np.array([1, 5, 6, 8, 10])
new_list = np.zeros(15, dtype=int)
new_list[test_list - 1] = test_list
new_list
array([ 1, 0, 0, 0, 5, 6, 0, 8, 0, 10, 0, 0, 0, 0, 0])
答案 3 :(得分:0)
嗯,你可以分步考虑一下。首先,我们必须使用全零来初始化列表。然后我们可以在您想要的位置填充您想要的值。
# Here's your test list
test_list = [1,5,6,8,10]
# Create a list of length 15 with all zeros
my_list = [0]*15
# Fill in the list with the values you have, you may want to check
# to make sure the value is in-bounds
for value in test_list:
if value <= 15 and value >= 1:
my_list[value-1] = value
else:
raise IndexError('Index ' + str(value) + ' is out of bounds!')
答案 4 :(得分:0)
#To insert random number of zeros between elements.
import random
t = [1,5,6,8,10]
#Generate a list of "list with one element of t and rand num of 0s"
a = [ [x] + [0]*random.randint(1,4) for x in t]
# a is list of list, and we do not want that. So, flatten out
# the each element of a and add them into list b.
b = []
for x in a: b = b + x
print('t', t)
print('b', b)
答案 5 :(得分:0)
要创建您拥有的输出,还可以使用简单的for
循环,如下所示:
test_list = [1, 5, 6, 8, 10]
new_list = [0] * 15 # create an empty list of 15 entries
for x in test_list:
new_list[x - 1] = x
print new_list
这将显示以下输出:
[1, 0, 0, 0, 5, 6, 0, 8, 0, 10, 0, 0, 0, 0, 0]
如果要将特定值与每个索引相关联,则可以使用元组对列表执行此操作,如下所示:
# Index,Value pairs
test_list = [(1, 10), (5, 3), (6, 5), (8, 1), (10, 2)]
new_list = [0] * 15
for index, value in test_list:
new_list[index - 1] = value
print new_list
然后会显示以下内容:
[10, 0, 0, 0, 3, 5, 0, 1, 0, 2, 0, 0, 0, 0, 0]