我对Python还不太熟悉,在我的程序中实际使用这种语言本身还是有困难的。以下是我目前所掌握的情况:
# Purpose: 'twolists' = takes 2 lists, & returns a new list containing
# alternating elements of lists.
# Return = final_list
# Parameter = list1, list2
def twolists(list1, list2): # don't forget to return final_list
alt_list = []
a1 = len(list1)
a2 = len(list2)
for i in range(# ? ):
# append one thing from list1 to alt_list - How?
# append one thing from list2 to alt_list - How?
现在该程序应该产生如下输出:
^{pr2}$
这将使用
zip_longest
fromitertools(这是标准库的一部分)来组合一个列表理解,将两个列表中的项交叉放入一个tuple
,默认情况下使用None
作为填充值。在这还使用
chain
也来自itertools
来展开列表。在最后,它从列表中过滤
None
项:或者按照@EliKorvigo的建议,使用
^{pr2}$ 测试itertools.chain.from_iterable
进行延迟迭代:基本方法:
您可以
zip()
正常情况下,如果两个列表的大小不同,则可以附加最大列表的其余部分:其工作原理如下:
^{pr2}$另一种可能的方法:
您还可以使用^{} 事先将列表转换为
deque()
对象,并用popleft()
弹出每个列表的开头,直到其中一个对象为空。你还不能把剩下的列表加起来。在下面是一个例子:
注意:这两种方法都是
O(n)
时间,这是此类问题的预期时间。在相关问题 更多 >
编程相关推荐