Im trying to find a way to sort the list by the sum of value of every character for each name, and so far the best i got is below. I have no idea how to sort the list while preserving it, but the output ends up being the ord numbers. Ive tried to use a copied list and to get the numbers from that list, but then I have no Idea how to use that to sort the original list.
I want to try to most of the code inside the function, so that it works with the other inputs (sum, length, first name, last name).
Relevant code here:
def namefunction()
global namelist
for i in range(0,len(namelist)):
namelist[i]=list(namelist[i])
for x in range(0, len(namelist[i])):
namelist[i][x]=ord(namelist[i][x])
return sum
print(*sorted(namelist, key= namefunction()), sep='\n')
Full code for reference here (not really necessary to look at)
print('You can sort by first name, last name, length, sum, or words .')
keycheck=input("What do you want to sort by? ")
namelist=['John S. Zmile', 'Giorno Giovana',
'Kakyoin Hanagashi', 'Trilaw Flanger', 'Stephane Locost',
'Bobert Hobert', 'Volvo B10BLE', 'Dale Reid', 'Annika Sörenstam',
'Cryt Fider', 'Valentine Prinsep', 'Gamrekeli Tony Toreli']
def namefunction():
if keycheck=="firstname":
return
elif keycheck=="last name":
return lambda x:x[x.rfind(' ') 1]
elif keycheck=="length":
return len
elif keycheck=="words":
return lambda x: -len(x.split())
elif keycheck =="sum":
global namelist
for i in range(0,len(namelist)):
namelist[i]=list(namelist[i])
for x in range(0, len(namelist[i])):
namelist[i][x]=ord(namelist[i][x])
return sum
print(*sorted(namelist, key= namefunction()), sep='\n')
CodePudding user response:
If I well understand, you want to sort a list of strings by the sum of their characters.
def value(char):
""" Return the position of the character in the alphabet. You could replace it by ord."""
if not char.isalpha():
return 0
return ord(char.lower()) - 96
def namefunction():
if keycheck == "firstname":
return lambda x: x.split()[0]
elif keycheck == "last name":
return lambda x: x.split(" ")[-1]
elif keycheck == "length":
return len
elif keycheck == "words":
return lambda x: len(x.split())
elif keycheck == "sum":
return lambda x: sum(map(value, x))
key = namefunction()
print(*sorted(namelist, key=key), sep='\n')