我是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?
Run Code Online (Sandbox Code Playgroud)
现在该程序应该产生如下输出:
outcome = twolists([ ], ['w', 'x', 'y', 'z'])
print(outcome)
['w', 'x', 'y', 'z']
outcome = twolists([0, 1], ['w', 'x'])
print(outcome)
[0, 'w', 1, 'x']
outcome = twolists([0, 1], ['w', 'x', 'y', 'z'])
print(outcome)
[0, 'w', 1, 'x', 'y', 'z']
outcome = twolists([0, 1, 2, 3], ['w', 'x'])
print(outcome)
[0, 'w', 1, 'x', 2, 3]
Run Code Online (Sandbox Code Playgroud)
def twolists(list1, list2):
newlist = []
a1 = len(list1)
a2 = len(list2)
for i in range(max(a1, a2)):
if i < a1:
newlist.append(list1[i])
if i < a2:
newlist.append(list2[i])
return newlist
Run Code Online (Sandbox Code Playgroud)
这使用zip_longest
来自itertools(它是标准库的一部分)的列表推导来将两个列表中的项交织成a tuple
,默认情况下None
用作fillvalue.
这还使用chain
也itertools
趋于平缓列表.
最后,它会过滤None
列表中的项目:
from itertools import chain, zip_longest
def twolists(l1, l2):
return [x for x in chain(*zip_longest(l1, l2)) if x is not None]
Run Code Online (Sandbox Code Playgroud)
或者根据@EliKorvigo的推荐,itertools.chain.from_iterable
用于懒惰迭代:
def twolists(l1, l2):
return [x for x in chain.from_iterable(zip_longest(l1, l2)) if x is not None]
Run Code Online (Sandbox Code Playgroud)
测试
In [56]: twolists([0, 1], ['w', 'x'])
Out[56]: [0, 'w', 1, 'x']
In [57]: twolists([0, 1], ['w', 'x', 'y', 'z'])
Out[57]: [0, 'w', 1, 'x', 'y', 'z']
In [74]: twolists([0, 1, 2, 3], ['w', 'x'])
Out[74]: [0, 'w', 1, 'x', 2, 3]
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1695 次 |
最近记录: |