14

I have a list of sets (using Python). Is there a way to print this without the "set([])" stuff around it and just output the actual values they are holding?

Right now I'm getting somthing like this for each item in the list

 set(['blah', 'blahh' blahhh')]

And I want it to look more like this

blah,blahh,blahhh

3 Answers3

18

Lots of ways, but the one that occurred to me first is:

s = set([0,1])
", ".join(str(e) for e in s)

Convert everything in the set to a string, and join them together with commas. Obviously your preference for display may vary, but you can happily pass this to print. Should work in python 2 and python 3.

For list of sets:

l = [{0,1}, {2,3}]
for s in l:
    print(", ".join(str(e) for e in s))
James Aylett
  • 3,332
  • 19
  • 20
4

I'm assuming you want a string representation of the elements in your set. In that case, this should work:

s = set([1,2,3])
print " ".join(str(x) for x in s)

However, this is dependent on the elements of s having a __str__ method, so keep that in mind when printing out elements in your set.

FastTurtle
  • 2,301
  • 19
  • 19
2

Assuming that your list of sets is called set_list, you can use the following code

for s in set_list:
    print ', '.join(str(item) for item in s)

If set_list is equal to [{1,2,3}, {4,5,6}], then the output will be

1, 2, 3
4, 5, 6
murgatroid99
  • 19,007
  • 10
  • 60
  • 95