我有两个列表,第一个列表保证只包含一个列表而不是第二个列表.我想知道创建一个新列表的最Pythonic方法,其中偶数索引值来自第一个列表,其奇数索引值来自第二个列表.
# example inputs
list1 = ['f', 'o', 'o']
list2 = ['hello', 'world']
# desired output
['f', 'hello', 'o', 'world', 'o']
Run Code Online (Sandbox Code Playgroud)
这有效,但并不漂亮:
list3 = []
while True:
try:
list3.append(list1.pop(0))
list3.append(list2.pop(0))
except IndexError:
break
Run Code Online (Sandbox Code Playgroud)
如何实现这一目标呢?什么是最Pythonic方法?
我是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', …Run Code Online (Sandbox Code Playgroud) 我希望能够交错两个可能长度不等的列表.我有的是:
def interleave(xs,ys):
a=xs
b=ys
c=a+b
c[::2]=a
c[1::2]=b
return c
Run Code Online (Sandbox Code Playgroud)
这适用于长度相等或只有+/- 1的列表.但是如果让我们说xs = [1,2,3]和ys = ["hi,"bye","no","yes","why"]这条消息出现:
c[::2]=a
ValueError: attempt to assign sequence of size 3 to extended slice of size 4
Run Code Online (Sandbox Code Playgroud)
如何使用索引修复此问题?或者我必须使用for循环?编辑:我想要的是让额外的值出现在最后.