简体   繁体   中英

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

I have a text file with a bunch of tuples in it. I want to filter the list so that if all numbers are odd, or if the sum of the numbers is less than 80, it will be removed. How can I parse the lists and do this filtering?

Input:

(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)

Output:

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

Algo:

  1. Read Input file and get lines
  2. Iterate every line from the lines by for loop
  3. eval line from string format to tuple fromat by ast
  4. check sum is less then 80 or not , if yes then continue to next line.
  5. check if all numbers from the line are odd or not.
  6. add to result list.
  7. Write result to output file.

Code:

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)

Output file:

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

Here is it:

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)

Output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM