我有两个长度为n和n + 1的列表:
[a_1, a_2, ..., a_n]
[b_1, b_2, ..., b_(n+1)]
Run Code Online (Sandbox Code Playgroud)
我想要一个函数给出一个列表,其中包含来自两者的备用元素,即
[b_1, a_1, ..., b_n, a_n, b_(n+1)]
Run Code Online (Sandbox Code Playgroud)
以下工作,但看起来不聪明:
def list_mixing(list_long,list_short):
list_res = []
for i in range(len(list_short)):
list_res.extend([list_long[i], list_short[i]])
list_res.append(list_long[-1])
return list_res
Run Code Online (Sandbox Code Playgroud)
任何人都可以建议更多的pythonic方式吗?谢谢!
我想通过定期扩展输入中给出的那些来构建一些列表(a,b,c,d).
周期性的结构是这样的,每个列表的第一个元素不能重复,而所有其他元素必须一直到达输入中设置的最大长度(周期可能不会重复整数次数).
举个例子,如果我有输入
a = [1, 2, 3, 4] max_len=11
Run Code Online (Sandbox Code Playgroud)
我想获得输出
a = [1, 2, 3, 4, 2, 3, 4, 2, 3, 4, 2]
Run Code Online (Sandbox Code Playgroud)
我写了这段代码:
for mylist in [a, b, c d]:
period = mylist[1:] # all elements but the first are repeated
while len(mylist)< max_len:
mylist.extend(period)
mylist = mylist[:max_len] # cut to max_len
print mylist
print a, b, c, d
Run Code Online (Sandbox Code Playgroud)
如果我运行这个,我从两个打印命令看到我的列表是我希望它们在程序仍处于循环中时的方式,但是当它们离开循环时它们会回到"非切片"长度,是,a回到大于max_len的长度,其中周期恰好重复4次:
a = [1, 2, 3, 4, 2, 3, 4, 2, 3, 4, 2, 3, 4]
Run Code Online (Sandbox Code Playgroud)
这是为什么?看起来该程序忘记了切片(但不是扩展名). …
python ×2