我試圖找到一種方法來按每個名稱的每個字符的值的總和對串列進行排序,到目前為止,我得到的最好的結果如下。我不知道如何在保留串列的同時對串列進行排序,但輸出最終是序號。我嘗試使用復制的串列并從該串列中獲取數字,但是我不知道如何使用它來對原始串列進行排序。
我想嘗試函式內的大部分代碼,以便它與其他輸入(總和、長度、名字、姓氏)一起使用。
相關代碼在這里:
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')
完整的代碼供參考(不是真的需要看)
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')
uj5u.com熱心網友回復:
如果我很好理解,您想按字串的字符總和對字串串列進行排序。
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')
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/441057.html
