【发布时间】:2019-02-15 16:46:27
【问题描述】:
我有一个名为 nums 的字符串列表。我正在尝试编写一个名为“last_char”的函数,它将这个字符串列表作为输入,并且只返回它的最后一个字符。我想使用这个函数 last_char 按每个字符串的最后一个字符/数字从最高到最低对名为“nums”的列表进行排序,使用 Python 中的 sorted 函数,我将使用“last_char”函数作为我的键.
我可以用 lambda 函数做到这一点,但我不能用定义的函数复制同样的东西。下面是我的带有 lambda 函数的代码和带有定义函数的不成功代码。
请解释我的代码定义的功能代码有什么问题。谢谢你的帮助。
'''working code using lambda function'''
nums = ['1450', '33', '871', '19', '14378', '32', '1005', '44', '8907', '16'] # this is input list to function, to get sorted based upon last character of each string
nums_sorted2 = sorted(nums, key=lambda x: x[-1], reverse=True)
print(nums_sorted2) # below is correct output
['19', '14378', '8907', '16', '1005', '44', '33', '32', '871', '1450'] # correct output as expected, using lambda function
定义的函数 - 我无法获得正确的输出
'''---Problem---'''
'''Defined function - where I can't get the correct output'''
nums = ['1450', '33', '871', '19', '14378', '32', '1005', '44', '8907', '16'] ## this is input list to function, to get sorted based upon last character of each string
lst=[]
def last_char(inp):
for x in nums:
lst.append(x[-1])
lst.sort(reverse=True)
return(lst)
print(last_char(nums))
#['9', '8', '7', '6', '5', '4', '3', '2', '1', '0']
nums_sorted = sorted(nums, key=last_char, reverse=False)
# incorrect output below
#['1450', '33', '871', '19', '14378', '32', '1005', '44', '8907', '16']
# Desired/expected output
# ['19', '14378', '8907', '16', '1005', '44', '33', '32', '871', '1450']
【问题讨论】: