Python Forum
Remove an item from a list contained in another item in python
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Remove an item from a list contained in another item in python
#6
>>> l = [[2,3,4,5],[2,3],[7,8],[2],[4,5,6]]
>>> S = sorted((set(x) for x in l), key=len, reverse=True)
>>> S
[{2, 3, 4, 5}, {4, 5, 6}, {2, 3}, {8, 7}, {2}]
>>> roots = []
>>> for s in S:
...     if not any(s.issubset(r) for r in roots):
...         roots.append(s)
... 
>>> roots
[{2, 3, 4, 5}, {4, 5, 6}, {8, 7}]
As supuflounder said, this is a O(n^2) algorithm, which means here that if the initial list has length N, we way call issubset() about N*(N-1)/2 times.
Reply


Messages In This Thread
RE: Remove an item from a list contained in another item in python - by Gribouillis - Nov-06-2021, 11:06 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  unable to remove all elements from list based on a condition sg_python 3 488 Jan-27-2024, 04:03 PM
Last Post: deanhystad
  return next item each time a function is executed User3000 19 2,370 Aug-06-2023, 02:29 PM
Last Post: deanhystad
  Copy item from one dict to another Pavel_47 3 1,051 Dec-23-2022, 11:19 AM
Last Post: Pavel_47
  Remove numbers from a list menator01 4 1,379 Nov-13-2022, 01:27 AM
Last Post: menator01
  code to send attachments contained on the drive. stefanoste78 1 910 Oct-12-2022, 02:16 AM
Last Post: Larz60+
  How to sort .csv file test log which item first fail and paint color SamLiu 24 5,124 Sep-03-2022, 07:32 AM
Last Post: Pedroski55
Question Finding string in list item jesse68 8 1,931 Jun-30-2022, 08:27 AM
Last Post: Gribouillis
  how to mouse click a specific item in pygame? Frankduc 5 1,774 May-03-2022, 06:22 PM
Last Post: Frankduc
  Can I check multi condition for 1 item in a easy way? korenron 4 1,605 May-01-2022, 12:43 PM
Last Post: deanhystad
  Remove empty keys in a python list python_student 7 3,108 Jan-12-2022, 10:23 PM
Last Post: python_student

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020