我有这段代码,我打算输出列表中的每个项目,然后将错误数计算为密码< 6 and password > 10,然后输出计数:
thislist = ["2021-07-22 16:24:42.843103, password < 6",
"2021-07-22 16:24:49.327202, password > 10",
"2021-07-22 16:24:44.963020, password < 6"]
newlist = []
i = 0
countersmall = 0
counterbig = 0
while i < len(thislist):
print(thislist[i])
i = i + 1
for y in thislist:
if " password < 6 " in y:
countersmall += 1
print("The number of errors:", countersmall)
如何只计算列表的一部分?看起来这段代码与“”内的整个文本匹配,因此我的输出是 0 而不是 2。 我尝试了 count 和 match index 方法,它们的输出相同,都是 0。
你写道:
if " password < 6 " in y:
你的意思是:
if " password < 6" in y:
请参考https://ericlippert.com/2014/03/05/how-to-debug-small-programs
这解决了它。你在 if 语句中多了一个 ' '
thislist = ["2021-07-22 16:24:42.843103, password < 6",
"2021-07-22 16:24:49.327202, password > 10",
"2021-07-22 16:24:44.963020, password < 6"]
newlist = []
i = 0
countersmall = 0
counterbig = 0
while i < len(thislist):
print(thislist[i])
i = i + 1
for y in thislist:
if "password < 6" in y:
countersmall += 1
print("The number of errors:", countersmall)
2021-07-22 16:24:42.843103, password < 6
2021-07-22 16:24:49.327202, password > 10
2021-07-22 16:24:44.963020, password < 6
The number of errors: 2
您在搜索字符串中有多余的空格。请注意,在
thislist
中,字符串"password < 6"
只有左边有一个空格而右边没有,而您的搜索字符串两边都有空格,这就是它不匹配的原因。要修复,只需将条件更改为if "password < 6" in y"
.
与您的问题无关,但您应该打印出项目并在一个循环中检查 for 条件。它会看起来更干净,更有效率。
for y in thislist:
print(y) # this replaces your while loop
if "password < 6" in y:
countersmall += 1
elif "password > 10" in y:
counterbig += 1