简体   繁体   中英

Writing a Set To a File in Python

I was wondering if there were any pre-made modules in python to remove the opening Set( and closing ) strings from the string:

set([`item1`,`item2`,`item3`])

so that it would be formatted like a list?

What you see is a set string representation . To get a list from a set , call list() on it:

>>> s = set(['item1', 'item2', 'item3'])
>>> s
set(['item2', 'item3', 'item1'])
>>> list(s)
['item2', 'item3', 'item1']

Keep in mind that sets are unordered collections .

There's a few different ways to accomplish this. The first two have already been mentioned in answers or comments, but I'd like to add some context as well as a third method.

1. Slice the String

As @Pynchia said in his comment, you can simply slice the result. This will work for any set and would be my preferred solution. Very simple:

>>> x = set(['item1','item2','item3'])
>>> print str(x)[4:-1]
['item2', 'item3', 'item1']

2. Convert to a List

As @alecxe said in his answer , you could simply convert the variable to a List and then convert to a String . However, this is mildly hackish because you're creating an entirely new List object with whatever overhead that entails just to get its string representation. Probably fine even for pretty large lists, but eventually the overhead will be meaningful.

>>> x = set(['item1','item2','item3'])
>>> print list(x)
['item2', 'item3', 'item1']

3. Create a new class

This might be overkill for your specific situation, but you could create your own Set subclass with its own string method. This code is assuming Python 2.

class mySet(set):
    def __str__(self):
        return super(Set,self).__str__()[4:-1]

And execution example:

>>> x = mySet(['item1','item2','item3'])
>>> print x
['item2', 'item3', 'item1']

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM