RGPython
RGPython

Reputation: 27

Breaking a Set into a List of Sets

I'm trying to read a text file and turn the pair of numbers inside the file into a list of sets.

Here is what my text file looks like:

4 #Number of pairs  
1 2
4 5
2 3
3 4

I've been able to turn the data from the text file into a list and then convert it into set but I end up getting a massive set instead of a list of sets like I would like.

Here's what my code currently looks like:

Input_File = input("Enter your file: ").lower()
with open(Input_File, 'r') as f:
    first_line = f.readline()
    data = f.read().splitlines()

set_of_pairs = set(data)
print(set_of_pairs)

Current Output:

{'1 2', '2 3', '4 5', '3 4'}

Desired Output:

[{'1 2'}, {'2 3'}, {'4 5'}, {'3 4'}]

Upvotes: 0

Views: 240

Answers (1)

gyre
gyre

Reputation: 16777

If you really want a list of one-element sets (which doesn't seem too useful), you can write:

Input_File = input("Enter your file: ").lower()
with open(Input_File, 'r') as f:
    first_line = f.readline()
    data = f.read().splitlines()

set_of_pairs = [{line} for line in data]
print(set_of_pairs) #=> [{'1 2'}, {'2 3'}, {'4 5'}, {'3 4'}]

However, it seems more likely that you would want a list of sets containing two integers each, as in:

Input_File = input("Enter your file: ").lower()
with open(Input_File, 'r') as f:
    first_line = f.readline()
    data = f.read().splitlines()

set_of_pairs = [{int(n) for n in line.split()} for line in data]
# Note that the order of pairs is not guaranteed
print(set_of_pairs) #=> [{1, 2}, {2, 3}, {4, 5}, {3, 4}]

Or even a list of tuples:

Input_File = input("Enter your file: ").lower()
with open(Input_File, 'r') as f:
    first_line = f.readline()
    data = f.read().splitlines()

set_of_pairs = [tuple(line.split()) for line in data]
print(set_of_pairs) #=> [(1, 2), (2, 3), (4, 5), (3, 4)]

Upvotes: 2

Related Questions