以特定方式填充列表 [英] Populating a list in a specific way
问题描述
我需要填充5个位置的列表.
I need to populate a list with 5 positions.
new_list = ___ ___ ___ ___ ___
我收到2个列表,并且有一个默认值来填充新列表.
I receive 2 lists and I have one default value to populate the new list.
现在开始问题:
好方法是,我从listA接收2个值,从listB接收2个值,并添加默认值
In the good way, I receive 2 values from listA and 2 values from listB and add the default value
A1 A2 DEFAULT B1 B2
但是现在,如果例如listA为空,则需要以另一种方式填充:
But now, if for example listA is empty I need to populate in another way:
DEFAULT B1 B2 B3 B4
如果listB为空,则相同.
the same if listB is empty.
如果listA仅包含1个元素,而listB具有另一个元素,则应为:
In case listA just has 1 element, and listB another element it should be:
A1 DEFAULT B1
listA和listB具有更多对象
the listA and listB have much more objects
推荐答案
您可以通过从默认用户开始递归地使用a和b来构建列表来解决此问题.
You can solve this by recursively building the list with a and b, starting with the default user.
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.如果两个列表中的任何一个为空,它将仅从该列表中不添加任何内容,从而提供确切的行为你自找的.
This will add one element of listA to the beginning and one element of listB to the end until the length of default is 5. if either of the lists becomes empty, it will simply add nothing from that list, giving the exact behavior you wanted.
一直持续到所有输入列表的长度为0或默认输入长度为5为止.此方法将对包括0在内的任何长度的列表起作用,但不会保留列表A中元素的顺序.
It keeps going until either all input lists are of length 0 or the default is of length 5. This method will work on lists of any length including zero, but will not preserve the ordering of the elements from list 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]
这篇关于以特定方式填充列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!