小编pmi*_*mit的帖子

迭代两个不同长度的列表

我有2个不同长度的数字列表,例如:

list1 = [1, 2, -3, 4, 7]
list2 = [4, -6, 3, -1]
Run Code Online (Sandbox Code Playgroud)

我需要使用函数迭代这些:

final_list = []
for index in range(???):
    if list1[index] < 0:
        final_list.insert(0, list1[index])
    elif list1[index] > 0:
        final_list.insert(len(final_list), list1[index])
    if list2[index] < 0:
        final_list.insert(0, list2[index])
    elif list2[index] > 0:
        final_list.insert(len(final_list), list2[index])
return final_list
Run Code Online (Sandbox Code Playgroud)

但无法弄清楚如何处理范围,因为如果我使用max长度,较短的列表将变得"超出范围" .有关如何克服这个或如何改变我的功能的任何想法?

python loops list

2
推荐指数
1
解决办法
6097
查看次数

标签 统计

list ×1

loops ×1

python ×1