我需要填充一个包含5个职位的列表。
new_list = ___ ___ ___ ___ ___
我收到2个列表,我有一个默认值来填充新列表。
现在开始出现问题:
好的方法是,我从listA收到2个值,从listB收到2个值并添加默认值
A1 A2 DEFAULT B1 B2
但是现在,如果例如listA为空,我需要以另一种方式填充:
DEFAULT B1 B2 B3 B4
如果listB为空,则相同。
如果listA只有1个元素,listB应该是另一个元素:
A1 DEFAULT B1
编辑:listA和listB有更多的对象
答案 0 :(得分:2)
您可以通过使用a和b递归构建列表来解决此问题,从默认用户开始。
def build_list(listA,listB,default=None):
if default is None:
default = [DEFAULT_USER]
if len(default) == 5 or len(listA) + len(listB) == 0:
return default
else:
default = listA[:1] + default + listB[:1]
return build_list(listA[1:],listB[1:],default)
这会将listA的一个元素添加到开头,将listB的一个元素添加到结尾,直到默认长度为5.如果其中一个列表变为空,则只会从该列表中添加任何内容,从而给出确切的行为你自找的。
它继续运行,直到所有输入列表的长度为0或默认值为长度为5.此方法适用于任何长度的列表,包括零,但不会保留列表A中元素的顺序。
一些经过测试的例子:
>>> DEFAULT_USER=1000
>>> build_list([1],[2])
[1,1000,2]
>>> build_list([],[1,2,3,4,5,6,7,8,9])
[1000, 1, 2, 3, 4]
>>> build_list([1,2,3,4,5],[6,7,8,9,10])
[2, 1, 1000, 6, 7]
>>> build_list([1,2,3,4,5,6,7,8,9],[])
[4, 3, 2, 1, 1000]
答案 1 :(得分:1)
这适用于所有情况,包括如果列表B的长度少于2个元素,而列表A的值为4或更高。
avail_a = len(list_a)
avail_b = min(len(list_b), 2) # assume that we are taking max 2 elements from B
num_a = min(avail_a, 4 - avail_b) # take either all of A (if len < 2), or remainder from the total
num_b = 4 - num_a # take (up to) remainder of total
final_list = list_a[:num_a] + [DEFAULT] + list_b[:num_b]
如果列表A和B中至少有2个元素,我们将从A中取2,从B中取2。
如果A中的元素少于2个avail_a < 4 - avail_b
,那么num_a == len(list_a)
。 num_b
将分配4个可用插槽的剩余部分。如果num_b
大于len(list_b)
,则list_b[num_b]
不会引发任何错误
如果B中的元素少于2个,则num_a
将等于4中剩余的广告位数,或len(list_a)
,以较小者为准。
答案 2 :(得分:1)
我认为你可以这样做:
new_list = [DEFAULT]
# First append listB elements from start until you reach the end
# or until you append enough elements according to the length of listA
i = 0
b_limit = min(len(listB), max(2, 4 - len(listA)))
while i < b_limit:
new_list.append(listB[i])
# Then prepend listA elements from end until you raech the start
# or until you've got a total of 5 elements.
i = 0
a_limit = min(len(listA), 5-len(new_list))
while i < a_limit:
new_list.insert(0, listB[-i-1])
应该是&#34;可以简化&#34;为:
new_list = listA + [DEFAULT] + listB
new_list = new_list[:(len(listA) + 1 + max(2, 4 - len(listA)))][-5:]
答案 3 :(得分:0)
您可以添加自己的列表:
new_list = listA + listB
# add the default value
new_list.append(DEFAULT)