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:
for loop
ast
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.