我知道,您可以在Python内部调用一个模块,但也可以在其内部取消它吗?这段代码应该只显示一次已找到的名称。它继续打印,直到我中断程序和从空闲的KeyboardInterrupt。我能帮些忙吗?我该放些什么或换什么?P.S.:我有Python 3.4.2
from array import *
s = ["Turner", "Philips", "Stevenson", "Jones", "Gonzalez",
"Whitaker", "Bruner", "Webster", "Foster", "Anderson",
"Klein", "Connors", "Rivers", "Wilson", "Duncan"]
g = [94, 82, 87, 78, 65,
90, 85, 97, 70, 100,
57, 88, 73, 92, 84]
s.sort()
for i in range(15):
idx = int(i)
studentList = s[idx]
gradeList = g[idx]
print(studentList, gradeList)
print("")
print("Student five: ", s[4], g[4])
print("Student ten: ", s[9], g[9])
print("Student fifteen: ", s[14], g[14])
gradeAverage = (g[0] + g[1] + g[2] + g[3] + g[4] + g[5] + g[6] + g[7] + g[8]
+ g[9] + g[10] + g[11] + g[12] + g[13] + g[14]) / 15
print("")
print("The average of the list of the grades is: ", gradeAverage)
print("The median of the list of grades is: ", g[7])
print("")
def byRank():
studentFound = False
index = 0
searchValue = input("Student to be found: ")
while(studentFound == False) & (index <= len(s) - 1):
if s[index] == searchValue:
studentFound == True
print("Name", searchValue, "was found at index", index)
else:
index = index + 1
print("Name not found. Searching...")
print("Name is not in the array.")
byRank()发布于 2015-02-18 19:57:34
实现byRank()函数的正确方法是使用为此目的创建的list.index()方法。试一试更像是:
def byRank():
searchValue = input("Student to be found: ")
try:
index = s.index(searchValue)
except ValueError:
print("Name is not in the array.")
else:
print("Name", searchValue, "was found at index", index)发布于 2015-02-18 19:57:10
studentFound == True不更改studentFound的值。使用单个=进行赋值。或者只需在这样一个简单的情况下使用break。
您通常不使用while循环来迭代Python中的序列--相反,如果您不想使用内置的index方法,这样的方法会更好:
for index, candidate in enumerate(s):
if candidate == searchValue:
print("Name", searchValue, "was found at index", index)
break但一次只有一个问题。
发布于 2015-02-18 19:59:14
代码中有几个错误。最大的错误是while循环测试。以下是修复方法
def byRank():
studentFound = False
index = 0
searchValue = raw_input("Student to be found: ")
while not studentFound and index < len(s):
if s[index] == searchValue:
studentFound = True
print("Name ", searchValue, " was found at index ", index)
else:
index += 1
print("Name not found. Searching...")
print("Name is not in the array.")FYI --汤姆·亨特的答案是如果你愿意放弃你的工作的话,写代码的更好的方法。
https://stackoverflow.com/questions/28592582
复制相似问题