在 python 中的给定列表中查找字符串

问题描述 投票:0回答:3

我有这段代码,我打算输出列表中的每个项目,然后将错误数计算为密码< 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。

python indexing nested-loops file-handling
3个回答
0
投票

你写道:

    if " password < 6 " in y:

你的意思是:

    if " password < 6" in y:

请参考https://ericlippert.com/2014/03/05/how-to-debug-small-programs


0
投票

这解决了它。你在 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

0
投票

您在搜索字符串中有多余的空格。请注意,在

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
© www.soinside.com 2019 - 2024. All rights reserved.