在不使用set的情况下从嵌套列表中删除重复项 [英] Removes duplicates from nested list without use of set

查看:50
本文介绍了在不使用set的情况下从嵌套列表中删除重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表列表,我想删除每个嵌套列表中的重复项.

I have a list of lists and I want to remove duplicates within each nested list.

Input: [['c', 'p', 'p'], ['a', 'a', 'a'], ['t', 't', 'p']]

Output: [['c', 'p'], ['a'], ['t','p']]

这里的关键是我不能使用 set() 函数或 fromkeys().

这是我的代码,

ans = []

for i in letters:
    [ans.append([x]) for x in i if x not in ans]

返回

[['c'], ['p'], ['p'], ['a'], ['a'], ['a'], ['t'], ['t'], ['p']]

这不是我想要的.

推荐答案

您可以遍历内部列表并检查该字符是否已存在

You can iterate over the inner list and check if that character is already present or not

inputList = [['c', 'p', 'p'], ['a', 'a', 'a'], ['t', 't', 'p']]
result = []

for l in inputList:
    # create a empty list to store intermediate result 
    tmp = []
    # iterate over sublist
    for ch in l:
        if ch not in tmp: tmp.append(ch)
    result.append(tmp)
print(result)

这篇关于在不使用set的情况下从嵌套列表中删除重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆