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] 

I want to sort the list "item_list" based on the author names. but while sorting i should ignore the special characters. Then the final output should be a list contaning Item2,Item4,Item1,Item3,Item5

1

There are 1 best solutions below

4
Martin Evans On BEST ANSWER

You could use a regular expression to create a list containing only the letters (so no special characters are considered) and sort based on that as follows:

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())

This would give you:

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

The re.findall('\w'), x) regular expression returns a list of just the characters contained in the author's name, thus removing all of the special characters. So for example the first item would be sorted using a sort key of:

['A', 'n', 'd', 'r', 'e', 'w', 'W', 'h', 'i', 't', 'e', 'h', 'e', 'a', 'd']