您可以使用正則表達式來創建僅包含字母的列表(因此不考慮特殊字符),並根據該列表將如下:
import re
class Item:
def __init__(self,item_name,author_name,published_year):
self.__item_name=item_name
self.__author_name=author_name
self.__published_year=published_year
def get_item_name(self):
return self.__item_name
def get_author_name(self):
return self.__author_name
def get_published_year(self):
return self.__published_year
Item1 = Item("The Book of Mormon", "Joseph smith Jr.", 1992)
Ietm2 = Item("Charlettes web", "E.B.White", 2013)
Item3 = Item("The prince of tides", "PatConroy", 2004)
Item4 = Item("Arise! Awake!", "Josephine", 1992)
Item5 = Item("Wonder", "R. J.Palacio", 2008)
item_list = [Item1, Ietm2, Item3, Item4, Item5]
new_item_list = sorted(item_list, key=lambda x: re.findall('\w', x.get_author_name()))
# For each class item in the new list, display its values
for item in new_item_list:
print "{}, {}, {}".format(item.get_item_name(), item.get_author_name(), item.get_published_year())
這將使你:
Charlettes web, E.B.White, 2013
Arise! Awake!, Josephine, 1992
The Book of Mormon, Joseph smith Jr., 1992
The prince of tides, PatConroy, 2004
Wonder, R. J.Palacio, 2008
的re.findall('\w'), x)
正則表達式返回的只是包含在作者姓名的人物名單,從而消除所有的特殊字符。因此,例如,第一個項目將使用排序鍵排序:
['A', 'n', 'd', 'r', 'e', 'w', 'W', 'h', 'i', 't', 'e', 'h', 'e', 'a', 'd']
請給我們一個預期輸出的例子。項目的定義是什麼?你是什麼意思的特殊字符? – DSLima90
項目是一類。 item1,item2,item3等是Item類的對象。 item_list是對象列表。我要排序基於屬性「作者」這是在項目類定義列表「item_list」。問題不考慮,如特殊字符對它們進行排序,‘‘「’,’ - 」等 – Jargon
上面,如果我給輸入作爲項目1 =項目(‘摩門之書’,「約瑟夫·史密斯小提的問題「,1992) Ietm2 = Item(」Charlettes web「,」EBWhite「,2013) Item3 = Item(」The prince of tides「,」PatConroy「,2004) Item4 = Item(」Arise!Awake!「 ,「Josephine」,1992) Item5 = Item(「Wonder」,「RJPalacio」,2008) new_item_list = [Item1,Ietm2,Item3,Item4,Item5]然後最終的輸出應該是[item2,Item4,Item1,項目3,項目5] – Jargon