2 回答
TA贡献1995条经验 获得超2个赞
我建议像下面的代码片段一样遍历名称,并将所有现有的首字母缩写保存在一个集合中:
all_names = [
'Risk Management',
'Scope Management',
'Stakeholder Management',
]
seen = set()
def find_initials(name, seen):
first, last = name.split()
for i in range(1, len(last)+1):
for j in range(1, len(first) + 1):
initials = first[:j] + last[:i]
if initials not in seen:
seen.add(initials)
return initials
# full name is found in seen!
for i in range(100):
initials = f'{first}{last}{i}'
if initials not in seen:
seen.add(initials)
return initials
initials = [find_initials(name, seen) for name in all_names]
print(initials) # ['RM', 'SM', 'StM']
TA贡献1802条经验 获得超6个赞
我找到了另一个解决方案
unique = list()
def unique_initials(full_name):
name_list = full_name.split()
initials = ''
for name in name_list:
initials += name[0]
if initials not in unique:
unique.append(initials)
return initials
else:
initials = ''
i=0
for name in name_list:
if i==0:
initials += name[:2]
i +=1
else:
initials += name[0]
return initials
Skills['Initials'] = Skills['Name'].apply(lambda x: unique_initials(x))
添加回答
举报