001.给定一个由正整数组成的列表nums,请编写一个函数,若某个元素出现重复,则将其左侧相同值的元素都移除,并返回余下的列表
题目来源:codcwars
# @-*- coding: utf-8 -*-
# @Author: 师玉幺叔
# @Software: Pycharm
"""
给定一个由正整数组成的列表nums,请编写一个函数,若某个元素出现重复,则将其左侧相同值的元素都移除,并返回余下的列表
"""
from collections import OrderedDict
def remove_left_number(target_list):
# 利用OrderedDict创建字典,OrderedDict会根据放入元素的先后顺序进行排序
dic01 = OrderedDict()
# 从后往前遍历列表
for i in range(len(target_list) - 1, -1, -1):
# 将元素作为键插入字典
dic01[target_list[i]] = None
# 清空列表
target_list.clear()
# 循环遍历字典,并将元素插入列表
for key in dic01:
target_list.append(key)
# 翻转列表
target_list.reverse()
if __name__ == '__main__':
list01 = [3, 4, 4, 3, 6, 3]
remove_left_number(list01)
# 输出结果:[4, 6, 3]
print(list01)
list02 = [1, 2, 1, 2, 1, 2, 3]
remove_left_number(list02)
# 输出结果:[1, 2, 3]
print(list02)
list03 = [1, 2, 3, 4]
remove_left_number(list03)
# 输出结果:[1, 2, 3, 4]
print(list03)