python - 返回一个新列表,该列表交错两个列表,但有一个扭曲
问题描述
def back_interleave(first, second):
if first == [] and second == []:
return []
elif first == []:
return second[::-1]
elif second == []:
return first[::-1]
else:
newlist = []
for i in range(len(first)-1, 0,-1):
newlist.append(first[i])
newlist.append(second[i])
for j in range(len(second)-len(first)-1,0,-1):
newlist.append(second[i])
return newlist
谁能告诉我我的代码对这个问题有什么问题。
解决方案
我不确定您的代码有什么问题,但是第二个和第三个 if 语句似乎使用了原始问题禁止的内置列表反转功能。
我要做的是确定较长列表的长度,然后向后遍历两个列表。
def back_interleave(first, second):
newlist = []
# You want to iterate through the length of the longer list
length = max(len(first), len(second))
for x in range(length):
# start appending elements from the back of the list
index = -1*(x+1)
if x < len(first):
newlist.append(first[index])
if x < len(second):
newlist.append(second[index])
return newlist
推荐阅读
- typescript - 将对象数组转换为特定键的值数组
- javascript - Jest 无法测试等待的承诺,而是超时
- html - 使用 CSS 的子元素上带有浅黑色背景的不透明度
- python - 为什么即使更改格式化文本中的变量(Python),打印格式化文本也保持不变
- c++ - 为什么 Google Protobuf 在 Mac 上使用我的 cpp 应用程序执行
- python - 如何根据另一列中的值填充一列中的 NaN?
- r - 参数 C 是否无法针对“nu-svr”进行优化,还是错误?
- java - 在java中创建数据类型
- reactjs - Redux Toolkit 错误处理问题
- qt5 - 具有固定大小的 Qt 中心表小部件