简体   繁体   English

如何将逗号分隔的数字字符串转换为数字?

[英]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模块中的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)

Output: Output:

256191252812371111341

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Django中将数字转换为逗号分隔的字符串 - How to convert number to comma separated string in Django 如何在Python中使用正则表达式从逗号分隔的数字字符串中找到下一个匹配数字的数字? - How to find next number to matched number from string of comma separated numbers using regular expression in Python? 如何将整数转换为逗号分隔的字符串 - How to convert an integer to a comma separated string 将用逗号分隔的字符串数字转换为整数或在python中浮点数 - convert string numbers separated by comma to integers or floats in python 如何在 python 中将逗号分隔的字符串转换为逗号分隔的 int - how to convert comma separated string to comma seperated int in python 如何将逗号分隔的字符串转换为 Python 中的项目中包含逗号的列表? - How to convert comma separated string to list that contains comma in items in Python? 如何将大量用逗号分隔的数字转换为float - How to convert a big list of comma-separated numbers into float 如何在 python 的列表中转换带有逗号分隔值的字符串? - how to convert a string with comma separated values within a list in python? 如何将包含未用逗号分隔的值列表的字符串转换为列表? - How to convert a string containing a list of values that are not comma-separated to a list? 如何在用空格而不是逗号分隔的字符串中组合数字? - How to combine a number in a string separated by a space instead of comma?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM