![](/img/trans.png)
[英]for and if/else loop with nested if statement not working in python
[英]Python if/else loop not working
我有一个csv文件所在的目录。 该代码读取文件并基于文件中的数据创建直方图。
但是,我试图这样做,以便在命令行中可以在csv文件中输入列标题之一,并且代码将仅绘制指定命令的图形。 示例:python histogram_maker.py“ C:/ Folder”区域。
我能够做到这一点,但是我想添加一个在用户输入csv文件中未指定的命令的情况下会产生错误消息的部件。 示例:周界不存在。 我的代码有什么问题? 即使存在某些内容,我也会在命令提示符下出现20次“不存在”,但它仍然生成我需要的所有文件。 如何停止这种重复并使之如此,以便仅当csv文件中没有某些内容时才会出现错误。
for column in df:
os.chdir(directory)
if len(sys.argv)>2:
for x in arguments:
if x.endswith(column):
#code for histogram
else:
print "does not exist"
您正在测试所有参数,即使只有一个匹配。 对于每个不匹配的参数,您将打印错误消息。
使用any()
函数查看是否存在任何匹配项:
if len(sys.argv)>2:
if any(x.endswith(column) for x in arguments):
#code for histogram
else:
print "does not exist"
或反转测试; not
使用并提早纾困:
if len(sys.argv)>2:
if not any(x.endswith(column) for x in arguments):
print "does not exist"
sys.exit(1)
#code for histogram
如果带有生成器表达式的any()
有点难以理解,您仍然可以使用for
循环,但是您需要使用break
尽早结束循环,然后使用else:
套件将在for
循环执行时执行没有提早退出:
for x in arguments:
if x.endswidth(column):
break # found a match
else:
# `for` loop was not exited, so no match found
print "does not exist"
sys.exit(1)
也许您想要这样的东西。
for column in df:
os.chdir(directory)
if len(sys.argv)>2:
found = False
for x in arguments:
if x.endswith(column):
found = True
#code for histogram
break
if (found == False):
print "does not exist"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.