删除重复代码调试

2024-10-17 08:19:09 发布

您现在位置:Python中文网/ 问答频道 /正文

作为一个python程序员新手,我一直在做一些练习,但我不明白为什么这段代码对我不起作用。你知道吗

现在我的练习是:

Define and test a function named removeDuplicates(somelist) that removes all duplicates from a given list and returns the remaining elements as a list while keeping the original order. Also define a main() function that calls on the removeDuplicates function for the given command line argument and prints the resulting list.

这是我目前的代码:

import sys

def main():
    userInput = int(input(""))
    removeDuplicates(somelist)
    print (unique)

def removeDuplicates(userInput):
    duplicate = set()
    unique = []   
    for x in userInput:
        if x not in duplicate:
            unique.append(x)
            duplicate.add(x)

    print (unique)

def removeDuplicates(somelist):
    duplicate = set()
    unique = [] 
    for line in sys.stdin:
        line = line.rstrip()
        if x not in sys.stdin:
            unique.append(x)
            duplicate.add(x)

    return unique

if __name__ =='__main__':
    main()

不管我做什么,我总是收到错误代码。此代码的错误代码为:

Traceback (most recent call last):
File "removeDuplicates.py", line 31, in <module>
main()
File "removeDuplicates.py", line 5, in main
removeDuplicates(somelist)
NameError: name 'somelist' is not defined`

Tags: andthe代码informaindefsys
2条回答

您没有被声明为somelist,它可能是这样的

......
userInput = int(input(""))
removeDuplicates(userInput)
......

此代码仅打印唯一值列表:

def main():
    userInput = input("Enter an integers, separated by spaces(' '):").split()
    unique = removeDuplicates(userInput)
    print(unique)

def removeDuplicates(userInput):
    unique = []
    for i in userInput:
        if i not in unique:
            unique.append(i)
    return unique

if __name__ =='__main__':
    main()

希望有帮助!你知道吗

相关问题 更多 >