List of paths

N

Nico Grubert

Dear Python developers

I have the following (sorted) list.
['/notebook',
'/notebook/mac',
'/notebook/mac/macbook',
'/notebook/mac/macbookpro',
'/notebook/pc',
'/notebook/pc/lenovo',
'/notebook/pc/hp',
'/notebook/pc/sony',
'/desktop',
'/desktop/pc/dell',
'/desktop/mac/imac',
'/server/hp/proliant',
'/server/hp/proliant/385',
'/server/hp/proliant/585'
]

I want to remove all paths x from the list if there is a path y in the
list which is part of x so y.startswith(x) is true.

The list I want to have is:
['/notebook', '/desktop', '/server/hp/proliant']

Any idea how I can do this in Python?

Thanks in advance
Nico
 
D

dorzey

You could use the followingm, where the_list is your list. (I'm new to
python so there might be a better way):

toremove = []
for x in the_list:
for y in the_list:
if y.startswith(x) and y != x:
toremove.append(y)

difference = filter(lambda x:x not in toremove, the_list)
 
P

Paul McGuire

Dear Python developers

I have the following (sorted) list.
['/notebook',
  '/notebook/mac',
  '/notebook/mac/macbook',
  '/notebook/mac/macbookpro',
  '/notebook/pc',
  '/notebook/pc/lenovo',
  '/notebook/pc/hp',
  '/notebook/pc/sony',
  '/desktop',
  '/desktop/pc/dell',
  '/desktop/mac/imac',
  '/server/hp/proliant',
  '/server/hp/proliant/385',
  '/server/hp/proliant/585'
]

I want to remove all paths x from the list if there is a path y in the
list which is part of x so y.startswith(x) is true.

The list I want to have is:
['/notebook', '/desktop', '/server/hp/proliant']

Any idea how I can do this in Python?

Thanks in advance
Nico

paths = ['/notebook',
'/notebook/mac',
'/notebook/mac/macbook',
'/notebook/mac/macbookpro',
'/notebook/pc',
'/notebook/pc/lenovo',
'/notebook/pc/hp',
'/notebook/pc/sony',
'/desktop',
'/desktop/pc/dell',
'/desktop/mac/imac',
'/server/hp/proliant',
'/server/hp/proliant/385',
'/server/hp/proliant/585'
]

seen = set()
basepaths = [ seen.add(s) or s for s in paths
if not any(s.startswith(ss) for ss in seen) ]

gives:

['/notebook', '/desktop', '/server/hp/proliant']

-- Paul
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,294
Messages
2,571,510
Members
48,195
Latest member
Tomjerry

Latest Threads

Top