[英]Why is my Python list iteration not working correctly?
我正在尝试制作一个脚本,有人可以在其中键入用户名,脚本将检查目录是否存在,并在遍历列表时返回 true 或 false。 目前,输出总是“未找到”/假,即使肯定至少应该返回一个真。
def scan():
username = input("Type in the username here: ")
i = 0
searchFor = folderList[i] + username
listLength = len(folderList)
while i < listLength:
if os.path.isdir(searchFor) == True:
print ("Folder found!")
i += 1
elif os.path.isdir(searchFor) == False:
print ("Not found")
i += 1
作为参考,下面不使用循环的这段代码工作正常,就好像我输入了用户名和存在的目录元素的正确索引一样,它返回真,否则如果我选择另一个索引,它是假的应该,所以这不是元素或文件夹权限的问题。
def test():
username = input("Type in the username here: ")
i = int(input("Type list index number here: "))
searchFor = folderList[i] + username
if os.path.isdir(searchFor) == True:
print("Folder found: " + searchFor)
else:
print("Not found!")
将不胜感激任何帮助!
我正在写一个答案,因为现有的答案未能解决问题,我认为它们比任何事情都更令人困惑。
您目前在循环之外有searchFor
。 其结果是,它会给出一个值一旦进入循环之前,那么它的价值从未改变。 如果你想改变它的值,你必须手动重新分配它:
while i < listLength:
searchFor = folderList[i] + username
虽然,实际上,这里应该使用for
循环(但不像@Sai 建议的那样):
for folder in folderList:
searchFor = folder + username
除了索引folderList
,您永远不会将i
用于任何其他用途,因此您应该直接迭代folderList
。 如果您只是使用数字来索引列表,则迭代range
通常被视为代码异味。
此代码将帮助您
def scan():
username = input("Type in the username here: ")
is_exists = False
for i in range(0,len(folderList)):
searchFor = folderList[i] + username
if os.path.isdir(searchFor):
is_exists = True
break
if is_exists:
print("Search is found")
else:
print("Not Found")
def scan():
username = input("Type in the username here: ")
i = 0
listLength = len(folderList)
while i < listLength:
searchFor = folderList[i] + username
if os.path.isdir(searchFor) == True:
print ("Folder found!")
i += 1
elif os.path.isdir(searchFor) == False:
print ("Not found")
i += 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.