我的文字文件如下;
5,6,7,3,4
6,3,4,7,5
etc
我如何在python中制定一条规则,检查每一行并查看是否:
如果两条规则都属实;我希望它能计算出真实的行数。
到目前为止,我已经尝试过:
count = 0
file = open('text.txt','r')
for line in file.readlines():
if "5" and "6" and "7" and "3" and "4" in line:
count+=1
答案 0 :(得分:1)
试试这个:
count = 0
required = '3,4,5,6,7'.split(',')
with open('text.txt') as file:
for line in file:
parts = line.strip().split(',')
if len(parts) == 5 and all(x in parts for x in required):
count += 1
print count
答案 1 :(得分:0)
您还可以使用以下代码:
target = ["3", "4", "5", "6", "7"]
count = 0
with open("input.txt") as input_file:
for line in input_file:
if sorted(line.strip().split(",")) == target:
count += 1
print(count)
其中input.txt
是:
5,6,7,3,4
6,3,4,7,5
blatantly invalid
6,4,3,5,7
3,4,5,6,7
3,8,5,6,7
这将具有
的预期输出4
这并没有明确检查长度,也没有对每个数字执行慢in
检查。它使用的事实是每个数字都存在,当且仅当排序列表等于target
时,长度恰好为5才为真。除了更简洁之外,它只使用快速(n log n
)排序和更快的列表比较。
你可以通过一个简单,懒惰的单行来实现同样的目标
with open("input.txt") as input_file:
count = sum(1 for line in input_file if sorted(line.strip().split(",")) == target)