Python列表提供帮助,列表中没有重复项

时间:2015-06-28 18:57:01

标签: python list

CheckList = ['hello', 'hello1', 'hello2', 'hello3', 'hello4', 'hello5', 'hello', 'hello1']
AlreadyChecked = ['hello', 'hello1', 'hello2', 'hello3', 'hello4']
NextCheck = ['hello', 'hello1', 'hello2']


while(CheckList):
    ToCheck = CheckList.pop()
    while(ToCheck in AlreadyChecked and CheckList):
        ToCheck = CheckList.pop()
    AlreadyChecked.append(ToCheck)
    while(ToCheck in NextCheck and CheckList):
        ToCheck = CheckList.pop()
    NextCheck.insert(0, ToCheck)

print(NextCheck)

此代码正在打印出来......

['hello', 'hello5', 'hello', 'hello1', 'hello2']

我需要做什么:

  • NextCheck打印后应该没有重复。
  • NextCheck应该包含CheckList中的所有内容,当然没有重复
  • 执行while(CheckList)后,NextCheck中的所有内容都应该在AlreadyChecked的某个地方

不幸的是,正如print语句所示,我在NextCheck中重复了一遍......

有任何帮助吗? :/

2 个答案:

答案 0 :(得分:4)

将您的列表转换为set()

lst = ["A", "B", "C", "C", "B"]
print(list(set(lst)))
>>> ["A", "B", "C"]

要更改列表,请执行

lst = set(lst)

答案 1 :(得分:0)

你错过了一些缩进。尝试粘贴这个并查看问题是否已修复。

CheckList = ['hello', 'hello1', 'hello2', 'hello3', 'hello4', 'hello5', 'hello', 'hello1']
AlreadyChecked = ['hello', 'hello1', 'hello2', 'hello3', 'hello4']
NextCheck = ['hello', 'hello1', 'hello2']


while(CheckList):
    ToCheck = CheckList.pop()
while(ToCheck in AlreadyChecked and CheckList):
    ToCheck = CheckList.pop()
AlreadyChecked.append(ToCheck)
while(ToCheck in NextCheck and CheckList):
    ToCheck = CheckList.pop()
    NextCheck.insert(0, ToCheck)
print(NextCheck)