过滤元组列表以删除所有奇数或总和小于 80 的列表

Filter list of tuples to removes lists with all odd number or sum less than 80

我有一个文本文件,里面有一堆元组。我想过滤列表,如果所有数字都是奇数,或者如果数字之和小于 80,它将被删除。我如何解析列表并进行过滤?

输入:

(1, 3, 14, 38, 31)
(2, 3, 17, 32, 39)
(7, 9, 11, 12, 16)
(12, 13, 14, 16, 17)
(14, 16, 18, 38, 40)
(15, 23, 27, 31, 39)

输出:

(1, 3, 14, 38, 31)
(2, 3, 17, 32, 39)
(14, 16, 18, 38, 40)

算法:

  1. 读取输入文件并获取行
  2. 迭代for loop
  3. 行中的每一行
  4. 从字符串格式到元组的 eval 行 ast
  5. 检查总和是否小于80,如果是则继续下一行。
  6. 检查该行中的所有数字是否都是奇数。
  7. 添加到结果列表。
  8. 将结果写入输出文件。

代码:

from ast import literal_eval


with open("input.txt") as fp, open("output.txt", "wb") as out:
    result = []
    for line in fp:
        tup = literal_eval(line.rstrip())
        if not all(ii % 2 for ii in tup) and sum(tup) >= 80:
            out.write(line)

输出文件:

(1, 3, 14, 38, 31)
(2, 3, 17, 32, 39)
(14, 16, 18, 38, 40)

这是它:

from ast import literal_eval


if __name__ == "__main__":
    with open("f.txt", 'r+') as f:
        s = f.read()

    with open("file.txt", 'w+') as f1:
        for x in s.split("\n"):
            if len(x) == 0:
                continue
            l = literal_eval(x)
            flt = [y for y in l if y % 2 == 0]
            if len(flt) == 0 or sum(l) < 80:
                continue
            print(x)
            f1.write("%s\n" % x)

输出:

(1, 3, 14, 38, 31)
(2, 3, 17, 32, 39)
(14, 16, 18, 38, 40)