【问题标题】:How to insert numbers at the end [duplicate]如何在末尾插入数字[重复]
【发布时间】:2020-12-11 13:09:02
【问题描述】:

我有这段代码可以对字符串中的字符进行排序并计算它的重复次数。

def char_repetition(str):
    
    reps = dict()
    word = [character.lower() for character in str.split()]
    word.sort()
    
    for x in word:
        if x in reps:
            reps[x] += 1
        else:
            reps[x] = 1

    return reps


for x in char_repetition(str):
    print (x,char_repetition(str)[x])

所以'1 2 3 2 1 a b c b a' 的输入会产生:

1   2
2   2
3   1
a   2
b   2
c   1

问题是我希望数字出现在输出的末尾,如下所示:

a   2
b   2
c   1
1   2
2   2
3   1

【问题讨论】:

标签: python sorting


【解决方案1】:

改变

    word = [character.lower() for character in str.split()]
    word.sort()

    digits = []
    chars = []
    for c in sorted(st.split()):
        if c.isdigit():
            digits.append(c)
        else:
            chars.append(c.lower())
    word = chars + digits

从 cmets 中的 ekhumoro,您可以使用自定义键对列表进行排序:

发件人:

    word = [character.lower() for character in str.split()]
    word.sort()

到:

    word = [character.lower() for character in str.split()]
    word.sort(key=lambda i: (1, int(i)) if i.isdigit() else (0, i))

【讨论】:

  • PS:如果列表中包含多位数字,最好是:word.sort(key=lambda i: (1, int(i)) if i.isdigit() else (0, i))
猜你喜欢
  • 2016-08-14
  • 1970-01-01
  • 2021-05-23
  • 2023-04-06
  • 1970-01-01
  • 2011-10-10
  • 1970-01-01
  • 1970-01-01
  • 2012-11-17
相关资源
最近更新 更多