Python:列表

时间:2017-03-26 02:50:28

标签: list python-3.x operations

给出这样一个列表:

sentence = ("george kendall", 7, "wally west", 21, "Joe montana", 17, "Alice Cooper")

我希望这样:

["Alice Cooper", "George Kendall", "Joe Montana", "Wally West", 45]

注意:名字和姓氏的第一个字母必须是大写字母,并且在列表的末尾是元组内所有整数的总和,所有元素都按字母顺序排序。

我可以使用下一个代码完成大部分任务:

def sortArtists(sentence):
    l = list(sentence)
    list_alpha = []
    list_digit = []

    for item in l:
        if isinstance(item, str):
            list_alpha.append(item)
        else:
            list_digit.append(item)

    add = sum(list_digit)
    arrange = sorted(list_alpha, key=str.lower)
    mystring = str(arrange).title()

    list(mystring).append(add)

    return mystring

print(sortArtists(("george kendall", 7, "wally west", 21, "Joe montana", 17, "Alice Cooper")))

理论上,在行list(mystring).append(add)中应该添加45的总和,它是列表中整数的总和但是没有发生。

我收到的所有内容都是:['Alice Cooper', 'George Kendall', 'Joe Montana', 'Wally West']但是列表末尾的内容丢失了45个。

如果我写在returnreturn mystring + str(add),我得到输出:

['Alice Cooper', 'George Kendall', 'Joe Montana', 'Wally West']45

但是45在分支之外,所以我可以做什么来完成整个任务?

感谢先进!!!

2 个答案:

答案 0 :(得分:0)

这可能是我想要的:

sentence = ("george kendall", 7, "wally west", 21, "Joe montana", 17, "Alice Cooper")

result = sorted([a.title() for a in sentence if type(a) == str],key = lambda x: x[0]) + [(sum([b for b in sentence if type(b) == int]))]

答案 1 :(得分:0)

这是您的代码,其中包含我在评论中建议的更改,以及其他一些小的更改。

def sort_artists(sentence):
    list_alpha = []
    list_num = []

    for item in sentence:
        if isinstance(item, str):
            list_alpha.append(item.title())
        else:
            list_num.append(item)

    total = sum(list_num)
    list_alpha.sort(key=str.lower)
    list_alpha.append(total)
    return list_alpha

sentence = ("george kendall", 7, "wally west", 21, "Joe montana", 17, "Alice Cooper")
result = sort_artists(sentence)
print(result)

<强>输出

['Alice Cooper', 'George Kendall', 'Joe Montana', 'Wally West', 45]