作为一名新手python程序员,我一直在做一些练习,但我不明白为什么这段代码对我不起作用。
现在我的练习是:
定义并测试名为removeDuplicates(somelist)的函数,该函数从给定列表中删除所有重复项,并在保持原始顺序的同时将其余元素作为列表返回。还定义一个main()函数,该函数调用给定命令行参数的removeDuplicates函数并打印结果列表。
到目前为止,这是我的代码:
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`
答案 0 :(得分:1)
您未被声明为somelist
,可能是这样,
......
userInput = int(input(""))
removeDuplicates(userInput)
......
答案 1 :(得分:0)
此代码只打印唯一值列表:
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()
希望它有所帮助!