[Tutor] Is there a simpler way to remove from a set?
Alan Gauld
alan.gauld at yahoo.co.uk
Sat May 8 06:19:14 EDT 2021
On 07/05/2021 13:04, Leam Hall wrote:
Hi Leam,
What I asked for was details of how "Python complained"
when you tried to do it without building 2 sets. It still
seems like you should be able to filter the elements in
a single pass...
However,
> def build_set_from_file(file):
> my_set = set()
> if Path(file).is_file():
> readfile = open(file, 'r')
> for line in readfile.readlines():
Files are iterable, just use
for line in open(file):
No need for readlines()
> line = line.strip()
> my_set.add(line)
> return my_set
And you could use a generator expression:
if Path(file).is_file():
return set(line.strip() for line in open(file))
> def build_dir_set(dirs):
> dir_set = set()
> for item in dirs:
> path = Path(item)
> parent = str(path.parent)
> dir_set.add(parent)
> return dir_set
Again, you could use a generator expression
but its getting a bit messier here.
return set(str(Path(item).parent()) for item in dirs)
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list