Reputation: 135
Code (incomplete):
list1 = ['1', '2', '3']
list2 = ['a', 'b', 'c']
list3 = ['12' '13' '14']
for list_in in list1:
with open("buffer_file") as f:
for line in f:
if len(line.split(" ")) >= 3:
var1 = line.split(" ")
if var1[0] == list1[0] and var[1] == list2[0] and var[3] == list3[0]:
buffer_file
:
no
priority enabled
1 a 12
2 b 13
3 d 14
pump it
What I am trying here is if in file line and list values are matched then print file line is matched.
Example 1:
list1[0], list2[0], list3[0]
is matched with line contains 1 a 12
values so print matched
Example 2:
list1[1], list2[1], list3[1]
is matched with line contains 2 b 13
values so print matched
Example 3:
list1[2], list2[2], list3[2]
is not matched because line contains 3 d 12
values print not matched and also print not matched element that is d
Any one please suggest me what is the best way get this done. I am struck in middle of my code.
Upvotes: 0
Views: 68
Reputation: 50190
You can zip
your three lists so that you can grab and check their values as triplets of aligned elements.
expected = zip(list1, list2, list3)
print expected
[ ('1', 'a', '12'), ('2', 'b', '13'), ... ]
If the lines in the file match your list elements one to one, you can then use zip()
again to loop through the expected and actual values together. zip()
is your friend. (If the file has extra lines, use a variable to walk down the list of triples.)
with open("buffer_file") as f:
for exp, actual in zip(expected, f):
if exp == actual.split(): # compares two 3-tuples
<etc.>
Upvotes: 1
Reputation: 1717
Reading between the lines a bit here. Essentially sounds line you want to ignore all the lines are't triples, enumerate over the file and find matches in your original list.
values = [
['1', '2', '3'],
['a', 'b', 'c'],
['12', '13', '14'],
]
def triples(line):
return len(line.split()) >= 3
with open("test_file.txt") as f:
content = filter(triples, (map(str.strip, f.readlines())))
# Loop over the file keeping track of index
for index, line in enumerate(content):
# Compare split line and triples
if line.split() == list(map(itemgetter(index), values)):
print(line)
Gives me, where "test_file.txt" contains your listed input
1 a 12
2 b 13
Upvotes: 0