gpt4 book ai didi

python - 在完全嵌套的 for 循环中返回值

转载 作者:行者123 更新时间:2023-12-01 01:12:17 26 4
gpt4 key购买 nike

我想要嵌套循环来测试所有元素是否匹配条件,然后返回 True。示例:

有一个给定的文本文件:file.txt,其中包含以下模式的行:

aaa:bb3:3

fff:cc3:4

字母、冒号、字母数字、冒号、整数、换行符。

一般来说,我想测试所有行是否都匹配这个模式。但是,在此函数中,我想检查第一列是否仅包含字母。

def opener(file):
#Opens a file and creates a list of lines
fi=open(file).read().splitlines()
import string
res = True
for i in fi:
#Checks whether any characters in the first column is not a letter
if any(j not in string.ascii_letters for j in i.split(':')[0]):
res = False
else:
continue
return res

但是,即使第一列中的所有字符都是字母,该函数也会返回 False。我也想请你解释一下。

最佳答案

您的代码评估代码后面的空行 - 因此False:

您的文件在最后一行之后包含换行符,因此您的代码会检查最后一个数据之后的行,但该行未满足您的测试 - 这就是为什么无论输入如何,您都会得到False:

aaa:bb3:3
fff:cc3:4
empty line that does not start with only letters

如果您“特殊处理”空行(如果它们出现在末尾),则可以修复它。如果填充行之间有空行,您也会返回 False:

with open("t.txt","w") as f:
f.write("""aaa:bb3:3
fff:cc3:4
""")

import string
def opener(file):
letters = string.ascii_letters
# Opens a file and creates a list of lines
with open(file) as fi:
res = True
empty_line_found = False
for i in fi:
if i.strip(): # only check line if not empty
if empty_line_found: # we had an empty line and now a filled line: error
return False
#Checks whether any characters in the first column is not a letter
if any(j not in letters for j in i.strip().split(':')[0]):
return False # immediately exit - no need to test the rest of the file
else:
empty_line_found = True

return res # or True


print (opener("t.txt"))

输出:

True
<小时/>

如果你使用

# example with a file that contains an empty line between data lines - NOT ok
with open("t.txt","w") as f:
f.write("""aaa:bb3:3

fff:cc3:4
""")

# example for file that contains empty line after data - which is ok
with open("t.txt","w") as f:
f.write("""aaa:bb3:3
ff2f:cc3:4


""")

你得到:False

关于python - 在完全嵌套的 for 循环中返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54734658/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com