简体   繁体   中英

Python Lists help, no duplicates in 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)

This code is printing out...

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

What I need to happen:

  • NextCheck should have no duplicates once it is being printed.
  • NextCheck should have everything in CheckList, no duplication of course
  • Once while(CheckList) is done executing, everything in NextCheck should be somewhere in AlreadyChecked

Unfortunately, as indicated by the print statement, I get repeats in NextCheck..

Any help? :/

Convert your list to a set()

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

To change the list just do

lst = set(lst)

You missed some indentation. Try pasting this and see if the problem is fixed.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM