在Python中从用户输入中查找重复值
我最初的代码是Python2.7.8中的一个基本计算器,但现在我决定加入一个用户可以输入多个值的函数 输入后,函数可以使用用户刚刚输入并存储在变量(函数参数)中的值运行,然后被告知它们是否输入了重复的值。目前,这些值在逗号处拆分,并插入到列表中,函数运行 我已经创建了一个函数,它已经接受了与用户输入'AlgorithmListEntry'相等的变量,当用户输入AlgorithmListEntry'时,就会发生这种情况在Python中从用户输入中查找重复值,python,Python,我最初的代码是Python2.7.8中的一个基本计算器,但现在我决定加入一个用户可以输入多个值的函数 输入后,函数可以使用用户刚刚输入并存储在变量(函数参数)中的值运行,然后被告知它们是否输入了重复的值。目前,这些值在逗号处拆分,并插入到列表中,函数运行 我已经创建了一个函数,它已经接受了与用户输入'AlgorithmListEntry'相等的变量,当用户输入AlgorithmListEntry'时,就会发生这种情况 def findDuplicates(AlgorithmListEntry):
def findDuplicates(AlgorithmListEntry):
for i in len(range(AlgorithmListEntry)):
for j in len(1,range(AlgorithmListEntry)):
if AlgorithmListEntry[i]==AlgorithmListEntry[j]:
return True
return False
函数也会查找参数的范围,但由于另一个错误,此操作不起作用
for i in len(range(AlgorithmListEntry)):
TypeError: range() integer end argument expected, got list.
我现在收到一个错误
for i in len(AlgorithmListEntry):TypeError: 'int' object is not iterable
为了便于查看,我只插入了与我的问题相关的代码部分
i = True #starts outer while loop
j = True #inner scientific calculations loop
def findDuplicates(AlgorithmListEntry):
for i in len(AlgorithmListEntry):
for j in len(1(AlgorithmListEntry)):
if AlgorithmListEntry[i]==AlgorithmListEntry[j]:
return True
return False
while i==True:
UserInput=raw_input('Please enter the action you want to do: add/sub or Type algorithm for something special: ')
scienceCalc=('Or type other to see scientific calculations')
if UserInput=='algorithm':
listEntry=raw_input('Please enter numbers to go in a list:').split(",")
AlgorithmListEntry = list(listEntry)
print AlgorithmListEntry
print "The program will now try to find duplicate values within the values given"
findDuplicates(AlgorithmListEntry)
#i = False
问题
len(range(foo))
而不是range(len(foo))
范围
如下所示:
range(end) --> [0, 1, 2, ..., end-1]
range(start, end) --> [start, start+1, ..., end-1]
range(start, end, step) --> [start, start+step, start+step*2, ..., end-1]
len
给出序列的长度,因此len([1,2,3,4,5])
是5
len(range([1,2,3]))
中断,因为range
无法接受列表作为参数
len([1,2,3])
中断,因为它以整数形式返回列表的长度,而整数是不可数的。这使您的线路看起来像:
for i in 3: # TypeError!
相反,您希望在AlgorithmListEntry
中设置尽可能多的数字范围
for i in range(len(AlgorithListEntry)):
# do stuff
Doh,你真的需要清理你的代码,关于PEP8,在希望很多人愿意阅读之前。说真的,在缩进上下功夫,用camelcase将名字绑定到一个列表中,如
AlgorithmListEntry=list(listEntry)
是可怕的:-)。