我有一个排序列表,如果它与列表中的模式匹配,我想插入一个字符串。
Example :
Sorted List
['Amy Dave', 'Dee Waugh', 'Eva A', 'Gin', 'Joy Kola', 'Kay Min', 'Mae', 'Pam Deing']
以上列表按排序顺序排列。我需要按排序顺序插入一个名称,如果名称已经存在,那么它应该在现有名称之前插入。
Example
Name 'Eva Henry'
由于Eva已经在列表中,因此在匹配模式后应该在“Eva A”之前插入。如果name不匹配,则应按列表中的排序顺序插入。输出应该是:
Sorted List
['Amy Dave', 'Dee Waugh', 'Eva Henry', 'Eva A', 'Gin', 'Joy Kola', 'Kay Min', 'Mae', 'Pam Deing']
任何帮助将不胜感激。
谢谢
答案 0 :(得分:3)
在我看来,没有愚蠢的问题。如果名称是全名,只有名字是排序的关键,那么总会有一些有趣的想法和解决问题的必要性。您可以这样使用bisect:
>>> fullnames = ['Amy Dave', 'Dee Waugh', 'Eva A', 'Gin', 'Joy Kola', 'Kay Min', 'Mae', 'Pam Deing']
>>> names = [full.split()[0] for full in fullnames]
>>> names
['Amy', 'Dee', 'Eva', 'Gin', 'Joy', 'Kay', 'Mae', 'Pam']
因此,我们有一个并行的名字列表,用于查找另一个全名xx
的位置(以与前一个案例相同的方式提取到x
的名字):
>>> xx = 'Eva Henry'
>>> x = xx.split()[0]
>>> x
'Eva'
现在,使用bisect在名字列表中找到想要的位置:
>>> import bisect
>>> pos = bisect.bisect_left(names, x)
然后更新两个列表:
>>> fullnames.insert(pos, xx)
>>> names.insert(pos, x)
结果如下:
>>> fullnames
['Amy Dave', 'Dee Waugh', 'Eva Henry', 'Eva A', 'Gin', 'Joy Kola', 'Kay Min', 'Mae', 'Pam Deing']
>>> names
['Amy', 'Dee', 'Eva', 'Eva', 'Gin', 'Joy', 'Kay', 'Mae', 'Pam']
答案 1 :(得分:0)
这是一个完整的答案,可以做你想要的,无论多么荒谬。我没有测试任何边缘情况。
sorta_sorted_list = ['Amy Dave', 'Dee Waugh', 'Eva A', 'Gin', 'Joy Kola', 'Kay Min', 'Mae', 'Pam Deing']
print sorta_sorted_list
def insert_kinda_sorted(name, sorta_sorted_list):
new_list = []
fname = name.split()[0]
inserted = False
for index in range(len(sorta_sorted_list)):
if not inserted:
if sorta_sorted_list[index].split()[0] == fname:
new_list.append(name)
inserted = True
if sorta_sorted_list[index] > name:
new_list.append(name)
inserted = True
new_list.append(sorta_sorted_list[index])
return new_list
sorta_sorted_list = insert_kinda_sorted('Eva Henry', sorta_sorted_list)
print sorta_sorted_list
sorta_sorted_list = insert_kinda_sorted('Joe Blow', sorta_sorted_list)
print sorta_sorted_list
输出是:
['Amy Dave', 'Dee Waugh', 'Eva A', 'Gin', 'Joy Kola', 'Kay Min', 'Mae', 'Pam Deing']
['Amy Dave', 'Dee Waugh', 'Eva Henry', 'Eva A', 'Gin', 'Joy Kola', 'Kay Min', 'Mae', 'Pam Deing']
['Amy Dave', 'Dee Waugh', 'Eva Henry', 'Eva A', 'Gin', 'Joe Blow', 'Joy Kola', 'Kay Min', 'Mae', 'Pam Deing']
答案 2 :(得分:0)
好的,我会为此投票,但我不能让这个立场。这是一种糟糕的设计模式,如果这是作业,你应该强烈抱怨。
我会将名称存储为具有频率的元组('Fred Bloggs',2),或使用dict()或其他东西:除了请不要这样。谷歌'python dict()'。
编辑:其实是dict()不是有序的吗?哦,我生命中失败了。耸肩。
编辑:我也是指元组列表。
答案 3 :(得分:0)
这是我的解决方案,我认为很容易
#spliting against whitespace
first_name = name.split()
#Stroting the first name of the user
first_name = first_name[0]
#Matching the pattern
match = re.compile(first_name,re.IGNORECASE)
ind = ''
for i in sort_names:
if re.match(match, i):
ind = sort_names.index(i)
break
#If name matches for the first time end the loop and do insert name in the sorted list
if ind != '':
sort_names.insert(ind, val)
print ""
print sort_names
else:
bisect.insort(sort_names, val)
print sort_names