[英]How to convert a comma separated string of numbers to a number?
I want to convert a comma separated list of numbers into the number itself and number of times each number appeared appended at the end of appearance of that number, like this:我想将逗号分隔的数字列表转换为数字本身以及每个数字出现的次数附加在该数字的出现末尾,如下所示:
"2,5,6,9,2,5,8,2,7,1,1,1,4"
If this is the string, removing the commas will give:如果这是字符串,删除逗号将给出:
2569258271114
But I want this:但我想要这个:
256191252823711341
Let say the number 2 appeared 3 times, so i want to write 3 after the last appearance of number '2' which appears in the above number at ...823...
.假设数字 2 出现了 3 次,所以我想在最后一次出现数字“2”之后写 3,它出现在上述数字...823...
And so on.等等。
I am stuck, I can do it the long way, but I need a short code.我被卡住了,我可以做很长的路,但我需要一个简短的代码。 A pythonic way of solving the problem:) Any help will be appreciated.解决问题的pythonic方法:)任何帮助将不胜感激。 TIA TIA
Here is how you can use Counter
from the collections
module, and str.find()
:以下是如何使用collections
模块中的Counter
和str.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)
Output: Output:
256191252812371111341
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.