[Tutor] Is there a simpler way to remove from a set?
Mats Wichmann
mats at wichmann.us
Fri May 7 09:57:42 EDT 2021
On 5/6/21 6:52 PM, Leam Hall wrote:
> Base code:
>
> ###
> def build_dir_set(my_list, exclude_dirs):
> my_set = set()
> for item in my_list:
> path = Path(item)
> parent = str(path.parent)
> my_set.add(parent)
> my_new_set = set()
> for exclude_dir in exclude_dirs:
> for parent in my_set:
> if re.match(exclude_dir, parent):
> my_new_set.add(parent)
> return my_set - my_new_set
> ###
>
> Where "my_list" and "exclude_dirs" are lists of directories
>
> For example, "my_list" might include:
> /opt/backup/home/me/Desktop/Documents/my_cool_file.txt
> /opt/backup/home/me/lang/git/software/src/cute_image.jpg
> /home/me/lang/git/this/noop.py
> /home/me/lang/git/that/anop.py
>
> And "exclude_dirs" might be"
> /home/me/lang/git
>
> The return should be a set of directories that do not start with any
> of the excluded directory names:
> /opt/backup/home/me/Desktop/Documents
> /opt/backup/home/me/lang/git/software/src
>
> I couldn't remove from the set during iteration, python complained.
> Hence having to make a second set.
To take Alan's reply down to an even shorter one:
The "simpler way" is to not add entries that don't qualify, then you
have nothing to remove. That requires a slightly different way of
thinking about your code.
There is, however, nothing wrong in general with using set operations
like you do to remove unwanted entries from a set.
More information about the Tutor
mailing list