Reputation: 11
I am trying to read two test files and compare their data in python. the text files look like:
x y
x y
x y
x y
and I am trying to compare the values of x in both lists and then see if they have the same y values. I'm not too stuck on the comparing part, but I can't understand how to turn the text files into a pair of lists that would be able to be compared.
I know I should be stripping the lines like so
with open('xy.txt', 'r') as f:
xy = [line.strip() for line in f]
but I don't know how to sort them so I could sort them with an algorithm afterward. Any help would be greatly appreciated!
Upvotes: 0
Views: 139
Reputation: 19684
A beginning example:
# Contents xy.txt
a 1
d 3
b 2
c 4
with open('xy.txt', 'r') as f:
xy = [line.strip().split() for line in f]
xy
[['a', '1'], ['d', '3'], ['b', '2'], ['c', '4']]
xy.sort()
xy
['a', '1'], ['b', '2'], ['c', '4'], ['d', '3']]
sort() has argument key=some_func. You can create a function that does custom sorting:
def y_sort(e):
return e[1]
xy.sort(key=y_sort)
xy
[['a', '1'], ['b', '2'], ['d', '3'], ['c', '4']]
Upvotes: 0
Reputation: 131
The code:
with open('xy.txt', 'r') as f:
xy = [line.strip() for line in f]
# Take the list of strings, where integers separated by space, and make a list of tuples of integers.
# For each line, separate on spaces, cast each to integer, and put in tuple.
lst = [(int(s.split(" ")[0]), int(s.split(" ")[1])) for s in xy]
print("Unsorted:", lst)
# Sort the list of tuples, using the first element then the second.
# Taken from: https://stackoverflow.com/questions/9376384/sort-a-list-of-tuples-depending-on-two-elements
lst = sorted(lst, key=lambda element: (element[0], element[1]))
print("Sorted:", lst)
The test textfile:
4 6
111 2
7 3
4 4
6 4
The output:
Unsorted: [(4, 6), (111, 2), (7, 3), (4, 4), (6, 4)]
Sorted: [(4, 4), (4, 6), (6, 4), (7, 3), (111, 2)]
See also this post.
Upvotes: 1