[英]exhaustive search over a list of complex strings without modifying original input
我正在嘗試創建一個最小的算法來詳盡地搜索字符串列表中的重復項並使用索引刪除重復項以避免更改單詞的大小寫及其含義。
需要注意的是,該列表包含 Blood、blood、DNA、ACTN4、34-methyl-O-carboxy、Brain、brain-facing-mouse、BLOOD 等詞。
我只想刪除重復的“血”字,保留第一個出現的首字母大寫,而不修改任何其他詞的大小寫。 關於我應該如何進行的任何建議?
這是我的代碼
def remove_duplicates(list_of_strings):
""" function that takes input of a list of strings,
uses index to iterate over each string lowers each string
and returns a list of strings with no duplicates, does not modify the original strings
an exhaustive search to remove duplicates using index of list and list of string"""
list_of_strings_copy = list_of_strings
try:
for i in range(len(list_of_strings)):
list_of_strings_copy[i] = list_of_strings_copy[i].lower()
word = list_of_strings_copy[i]
for j in range(len(list_of_strings_copy)):
if word == list_of_strings_copy[j]:
list_of_strings.pop(i)
j+=1
except Exception as e:
print(e)
return list_of_strings
制作字典{text.lower():text,...}
,使用鍵進行比較並將文本的第一個實例保存在值中。
d={}
for item in list_of_strings:
if item.lower() not in d:
d[item.lower()] = item
d.values() 應該是你想要的。
我認為像下面這樣的東西可以滿足你的需要:
def remove_duplicates(list_of_strings):
new_list = [] # create empty return list
for string in list_of_strings: # iterate through list of strings
string = string[0].capitalize() + string[1:].lower() # ensure first letter is capitalized and rest are low case
if string not in new_list: # check string is not duplicate in retuned list
new_list.append(string) # if string not in list append to returned list
return new_list # return end list
strings = ["Blood", "blood", "DNA", "ACTN4", "34-methyl-O-carboxy", "Brain", "brain-facing-mouse", "BLOOD"]
returned_strings = remove_duplicates(strings)
print(returned_strings)
(供參考,這是寫在 Python 3.10 中的)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.