天天看點

python-正負數交叉排序

'''
正負數交叉排序
例如,
輸入:[5, -5, 3, -3, 9, 8, 0, 1, -9, -8, -7, -6],
輸出:[5, -5, 3, -3, 9, -9, 8, -8, 0, -7, 1, -6]
'''


def sortzhengfu(list):
    list1 = []
    list2 = []
    for i in range(len(list)):
        if list[i] >= 0:
            list1.append(list[i])
        else:
            list2.append(list[i])
    print(list1)
    print(list2)
    list3 = []
    if len(list1) >= len(list2):
        for i in range(len(list2)):
            list3.append(list1[0])
            del list1[0]
            list3.append(list2[i])
        list3.extend(list1)
    else:
        for i in range(len(list1)):
            list3.append(list1[i])
            list3.append(list2[0])
            del list2[0]
        list3.extend(list2)
    return list3


if __name__ == '__main__':
    list = [5, -5, 3, -3, 9, 8, 0, 1, -9, -8, -7, -6]
    print(sortzhengfu(list))