Partitioning a list in Python -


i find out how modify contents of list, filenames have been returned os.listdir().

the filenames consist of number of duplicate names followed underscore, suffix, , file extension. i'm trying cut elements in list down first part of filename, before '_', so:

apple_d.jpg apple_si.jpg apple_sg.jpg 

becomes single entry in list, 'apple'.

i'm able rid of duplicates , re-alphabetise with

list(sorted(set(t))) 

but getting rid of underscore onwards proving tricky. tried via .rpartition("_")[0]. apparently doesn't work lists. i'm wondering how go this?

edit: well, not working here. still getting duplicates , no splitting.

objects = os.listdir(dir)          object in objects:         sorted(set(object.split('_', 1)[0]))         cmds.menuitem(label = object, parent = "objectmenu") 

(the last command maya command, populates option menu). tired i'll have take later. date. sure soon.

use str.split() or str.rsplit() limit, select first element:

filename.split('_', 1)[0] 

.rsplit('_', 1) split on last underscore, .split() on first. pick 1 fits usecase best.

this gives before first or last underscore filename.

using in set comprehension, sorted() returning list set:

unique_prefixes = sorted({filename.split('_', 1)[0] filename in os.listdir(somedir)}) 

for python 2.6 , earlier, don't yet have set comprehension syntax, following generator expression set() work too:

unique_prefixes = sorted(set(filename.split('_', 1)[0] filename in os.listdir(somedir))) 

Comments

Popular posts from this blog

python - How to create a legend for 3D bar in matplotlib? -

java - Multi-Label Document Classification -

php - Dynamic url re-writing using htaccess -