1

我有一个按以下格式组织的姓名和地址列表:

Mr and Mrs Jane Doe  
Candycane Lane  
Magic Meadows, SC 

我有几个这样写的数据块,我希望能够按姓氏(Doe,在这种情况下)按字母顺序排列每个块。在做了一些挖掘之后,我能想到的最好的办法是我需要制作一个“列表列表”,然后使用姓氏作为按字母顺序排列块的键。然而,由于对 python 的新鲜度和缺乏谷歌技能,我能找到的最接近的是这个. 我对将每个块转换为列表然后对其进行切片感到困惑;我似乎无法找到一种方法来做到这一点,但仍然能够正确地按字母顺序排列。非常感谢任何和所有指导。

4

3 回答 3

2

If I understood correctly, what you want basically is to sort values by "some computation done on the value", in this case the extracted last name.

For that, use the key keyword argument to .sort() or sorted():

def my_key_function(original_name):
    ## do something to extract the last name, for example:
    try:
        return original_name.split(',')[1].strip()
    except IndexError:
        return original_name

my_sorted_values = sorted(my_original_values, key=my_key_function)

The only requirement is that your "key" function is deterministic, i.e. always return the same output for each given input.

You might also want to sort by last name and then first name: in this case, just return a tuple (last, first): if last si the same for two given items, first will be used to further sort the two.

Update

For your specific case, this function should do the trick:

def my_key_function(original_name):
    return original_name.splitlines()[0].split()[-1]
于 2013-01-01T19:16:29.023 回答
2

您想创建一个新列表,其中每个条目都是一个元组,其中包含您想要的排序键和整个内容。对该列表进行排序,然后获取排序中每个条目的第二个组成部分:

def get_sort_name (address):
    name, address, city = address.split('\n')
    return (name.split(' ')[-1] , address) # last item of first line & whole thing as tulle


keyed_list = map (get_sort_name, addresses)
keyed_list.sort()
sorted_addresses = [item[1] for item in keyed_list]

当然,使用 lambdas 可以更紧凑,但可读性更好:)

于 2013-01-01T19:20:31.317 回答
2

假设您已经在列表中有数据

l = ['Mr and Mrs Jane Smith\nCandycane Lane\nMagic Meadows, SC',
     'Mr and Mrs Jane Doe\nCandycane Lane\nMagic Meadows, SC',
     'Mr and Mrs Jane Atkins\nCandycane Lane\nMagic Meadows, SC']

您可以指定要排序的键。

l.sort(key=lambda x: x.split('\n')[0].split(' ')[-1])

.split(' ')[-1]在这种情况下,获取第一行 ( ) 上的最后一个单词 ( .split('\n')[0])

于 2013-01-01T19:24:23.433 回答