【问题标题】:How to convert a comma separated string of numbers to a number?如何将逗号分隔的数字字符串转换为数字?
【发布时间】:2025-12-10 05:20:03
【问题描述】:

我想将逗号分隔的数字列表转换为数字本身以及每个数字出现的次数附加在该数字出现的末尾,如下所示:

"2,5,6,9,2,5,8,2,7,1,1,1,4"

如果这是字符串,删除逗号将给出:

2569258271114

但我想要这个:

256191252823711341

假设数字 2 出现了 3 次,所以我想在数字“2”最后一次出现之后写 3,它出现在上面的数字 ...823... 中。 以此类推。

我被卡住了,我可以做很长的路,但我需要一个简短的代码。解决问题的pythonic方式:)任何帮助将不胜感激。 TIA

【问题讨论】:

  • 你想要字符串还是整数格式的答案?

标签: python string count integer concatenation


【解决方案1】:

以下是如何使用 collections 模块中的 Counterstr.find()

from collections import Counter

s = "2,5,6,9,2,5,8,2,7,1,1,1,4"
s = s.replace(',','') # Removes all commas
n = Counter(s) # Dictionary with different numbers as keys and their frequency as values

for a in n: # For every different number in n
    i = s.rfind(a) # Finds the index of the last appearance of the number
    s = s[:i+1]+str(n[a])+s[i+1:] # Inserts the frequency of the number on the right of the last appearance of it
    
print(s)

输出:

256191252812371111341

【讨论】:

  • 非常感谢 :),你是最棒的。那很快。伟大的。现在标记为正确答案。