This is a commonly asked question but I've not found an answer on searches that meets the exact kind of thing I'm trying.
I have a list of items with similar names and I want to add them with a number suffix so that each time, if a duplicate exists, the new item will be incremented to be unique. All the answered searches I found don't split names in character and number. And I need to do that because I'm not just working the original list, I want to append a new item with a unique name. So, I extract a sublist matching the item type, sort it alpha-numerically, split the last item into suffix and prefix, increment the numerical suffix by 1, reform a new item name and append it to the end of the original list. All fine there. Maybe this isn't the most efficient approach but open to suggestions.
Say I have existing list:
mylist = ["point1", "feature1", "point2", "area1", "point3", "feature2", "area2"]
And say if I add a new item point
or feature
item, it will be automatically renamed point4
or feature3
.
So I get the new string name result I want but my final list never appends the newly created item. Where am I going wrong?
So far I have this:
from collections import Counter
mylist = ["point1", "feature1", "point2", "area1", "point3", "feature2", "area2"]
def mysplit(s):
head = s.rstrip('0123456789')
tail = s[len(head):]
return head, tail
# extract items starting with specified string into separate sub list
sublist = [x for x in mylist if x.startswith('point')]
# sort sub list alpha-numerically
sublistSort = sorted(sublist, key=lambda item: (int(item.partition(' ')[0])
if item[0].isdigit() else float('inf'), item))
print(sublistSort[-1])
counts = Counter(sublistSort)
for s,num in counts.items():
if num > 1: # ignore unique names
# get last element of sorted sub list
number = sublistSort[-1]
# split name and number elements
number_split = mysplit(number)
# increment number
number_inc = number_split[1] + 1
# form new element name
new_number = number_split[0] + number_inc
# append new element name to original list
mylist.append(new_number)
print('#########')
print(mylist)
EDIT: so this works, I just need to wrap into a function now. Still interested if anyone thinks of better method using fancy sorting methods etc.,.
mylist = ["point1", "feature1", "point2", "area1", "point3", "feature2", "area2"]
def mysplit(s):
head = s.rstrip('0123456789')
tail = s[len(head):]
return head, tail
# extract items starting with specified string into separate sub list
sublist = [x for x in mylist if x.startswith('point')]
# sort sub list alpha-numerically
sublistSort = sorted(sublist, key=lambda item: (int(item.partition(' ')[0])
if item[0].isdigit() else float('inf'), item))
print(sublistSort[-1])
number = sublistSort[-1]
number_split = mysplit(number)
number_inc = str(int(number_split[1]) + 1)
new_number = number_split[0] + number_inc
mylist.append(new_number)
print('#########')
print(mylist)