如何使用两个for循环来检查列表中的行是否等于变量



对于个人项目,我需要使用两个For循环从文本文件提取数据到列表。之后,python需要读取列表并检查变量lower_than_six("password <6")greater_than_ten("password>10")出现在代码中。但由于某种原因,它没有这样做。我写的代码:

def main():
lower_than_six = "password < 6"
greater_than_ten = "password > 10"
input_file = "ITWorks_password_log.txt"
f = open(input_file, "r")
counter_pw_too_small = 0
counter_pw_too_large = 0
for line in f.readlines():
attempts_list = line.strip()
print(attempts_list)
for line in attempts_list:
if lower_than_six in line:
counter_pw_too_small += 1
elif greater_than_ten in line:
counter_pw_too_large += 1
print(f"n Password < 6 occurred {counter_pw_too_small} times")
print(f"n Password > 10 occurred {counter_pw_too_large} times")
main()

您应该稍微修改一下代码。这样的:

def main():
lower_than_six = "password < 6"
greater_than_ten = "password > 10"
input_file = "ITWorks_password_log.txt"
f = open(input_file, "r")
counter_pw_too_small = 0
counter_pw_too_large = 0
attempts_list = []
for line in f.readlines():
attempt = line.strip()
attempts_list.append(attempt)
print(attempt)
for line in attempts_list:
if lower_than_six in line:
counter_pw_too_small += 1
elif greater_than_ten in line:
counter_pw_too_large += 1
print(f"n Password < 6 occurred {counter_pw_too_small} times")
print(f"n Password > 10 occurred {counter_pw_too_large} times")
main()

您每次都将attempts_list定义为行,因此最后它只是文件的最后一行。相反,您需要启动它,然后向其追加行。

顺便说一下,我假设你的缩进就像这样,由于复制粘贴,否则你需要修复缩进,使函数行在(main())函数内。

我的测试文本文件:
blablalkdslkfvsdf
sdfglksdfglkpassword < 6dflgkld kfgdfg df
sdfgsd fgdfg sdfghpassword < 6dfghdgf 
sdfhgdfghsfdghfgb password < 6 ghs dgfh sdfghdfghdgfdsfgs
sdfg sdfg sdfg sdfghdfghdgfdsfgs
sdfg spassword > 10df 
sdfgsdghdfgh 

输出:

blablalkdslkfvsdf
sdfglksdfglkpassword < 6dflgkld kfgdfg df
sdfgsd fgdfg sdfghpassword < 6dfghdgf
sdfhgdfghsfdghfgb password < 6 ghs dgfh sdfghdfghdgfdsfgs
sdfg sdfg sdfg sdfghdfghdgfdsfgs
sdfg spassword > 10df
sdfgsdghdfgh
Password < 6 occurred 3 times
Password > 10 occurred 1 times

如果2 loops不是您需要完成的困难要求,那么它非常简单。您可以使用str.count()函数并打印出现次数。

参见示例:

lower_than_six = "password < 6"
greater_than_ten = "password > 10"
input_file = "ITWorks_password_log.txt"
file_content = open(input_file, "r").read()
print(f"n Password < 6 occurred {file_content.count(lower_than_six)} times")
print(f"n Password > 10 occurred {file_content.count(greater_than_ten)} times")

如果您需要使用循环,同样,2不是必需的-您可以使用1。如,

def main():
lower_than_six = "password < 6"
greater_than_ten = "password > 10"
input_file = "I1.txt"
file_lines = open(input_file, "r").readlines()
counter_pw_too_small = 0
counter_pw_too_large = 0
for line in file_lines:
if lower_than_six in line:
counter_pw_too_small += 1
elif greater_than_ten in line:
counter_pw_too_large += 1
print(f"n Password < 6 occurred {counter_pw_too_small} times")
print(f"n Password > 10 occurred {counter_pw_too_large} times")

最新更新