【每日一题0613】删除 list 里面的重复元素 并保持顺序不变化

删除list 里面的重复元素 并保持顺序不变化
例 [1,2,4,2,4,3] 变成 [1,2,4,3]

nums_list = [1,2,4,2,4,3]
res_list =
for i in nums_list:
if i not in res_list:
res_list.append(i)

set强转会改变顺序

是的 没注意到 :sweat_smile:

用列表推导式比较方便。
list1=[1,2,4,2,4,3]
list2=[list2.append(i) for i in list1 if i not in list2]
print(list2)

list3 = [1,2,4,2,4,3]
list3.reverse()
for i in list3:
for _ in range(list3.count(i)):
if list3.count(i) > 1:
list3.remove(i)
list3.reverse()

"""
删除list 里面的重复元素 并保持顺序不变化
例 [1,2,4,2,4,3] 变成 [1,2,4,3]
"""


def test(test_list: list):
    i = 0
    while i < len(test_list):
        if test_list[i] in test_list[0:i]:
            test_list.pop(i)
        else:
            i += 1
    return test_list


assert test([1, 2, 4, 2, 4, 3]) == [1, 2, 4, 3]
assert test([1, 2, 2, 2, 2, 1]) == [1, 2]
assert test([]) == []

解法1: 列表中都是纯数字。

def single_num_list(li):
    return sorted(set(li), key=lambda x:li.index(x))
assert single_num_list([1,2,4,2,4,3]) == [1,2,4,3]

解法2: 凡是列表中的对象是可散列的都适用。例如数字,字符串和元组。

def single_hashable(li):
    existed = set()
    for x in li:
        if x not in existed:
            yield x
            existed.add(x)
    
assert list(single_hashable([1,2,4,2,4,3])) == [1,2,4,3]

“”"
每日一题:删除list 里面的重复元素 并保持顺序不变化
例 [1,2,3,2,4,3] 变成 [1,2,3,4]

“”"
alist = [1, 5, 2, 3, 5, 3, 2, 4, 3, 6]
blist =
for i in alist:
if i in blist:
pass
else:
blist.append(i)
print(blist)

lst_1 = [1,2,4,2,4,3]
lst_2 =
for i in lst_1:
if i not in lst_2:
lst_2.append(i)
print(lst_2)

def func2(sss):
    #用字典result,将元素放入key(key不能重复)
    result = { i:'a' for i in sss }
    list_1 = result.keys()
    return list(list_1)
print(func2([1, 3, 2, 2, 3, 5, 5, 4, 4]))

a=[1,2,4,2,4,3]
b=list(set(a))
b.sort(key=a.index)
print(b)

关闭