我想根据该对象的属性对对象列表进行排序,而不考虑特殊字符

时间:2017-05-03 12:59:47

标签: python

  Item1=Item("The Book of Mormon","Joseph smith Jr.",1992 ) 
   Item2=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,Item2,Item3,Item4,Item5] 

我想根据作者姓名对列表“item_list”进行排序。但排序时我应该忽略特殊字符。然后最终输出应该是包含Item2,Item4,Item1,Item3,Item5

的列表

1 个答案:

答案 0 :(得分:3)

您可以使用正则表达式创建仅包含字母的列表(因此不会考虑特殊字符),并根据以下内容进行排序:

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']