把一个数转换成另一个数

2024-06-01 04:00:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一系列的数字,比如:

1234
5678
778899

我想把它们转换成一种形式,从尽可能小的数字开始

示例:

5678 would be 1234
778899 would be 112233
2452 would be 1231

我试着做:

index = 0
digit = 1
newCode = []
newCode.append(digit)

while index != len(codice)-1:
    index += 1

    if code[index] == code[index-1]:
        newCode.append(digit)

    else:
        digit += 1
        newCode.append(digit) 

但是它把5675这样的数字转换成1234,所以它不起作用。 有没有更好的方法,我做错了什么?你知道吗


Tags: 示例indexlenifcode数字beelse
3条回答
t = {}
int(''.join(t.setdefault(d, str(len(t) + 1)) for d in str(n)))

演示:

>>> for n in 5678, 778899, 2452:
        t = {}
        print(n, '->', int(''.join(t.setdefault(d, str(len(t) + 1)) for d in str(n))))

5678 -> 1234
778899 -> 112233
2452 -> 1231

您只检查数字是否等于最后一个数字,但这不适用于2452。你必须用a dictionary,如@wjmccann answer,跟踪所有过去的数字。你知道吗

不过,您可以通过将^{}^{}结合起来,将这个过程缩短一点。defaultdict将记住已经看到的数字,count为新的数字提供值。你知道吗

import itertools, collections, functools

def convert(n):
    d = collections.defaultdict(functools.partial(next, itertools.count(1)))
    return int(''.join(str(d[x]) for x in str(n)))

print(convert(5678))   # 1234
print(convert(778899)) # 112233
print(convert(2452))   # 1231

甚至更短,如建议的in comments

def convert(n):
    d = collections.defaultdict(list("987654321").pop)
    return int(''.join(d[x] for x in str(n)))

它再次使用defaultdict,但是使用数字列表中的pop作为工厂函数,在需要新数字时从列表末尾删除元素。你知道吗

这可以通过字典实现:

编辑:所以我可能误解了这个问题。从例子中我推测这意味着将第一个数字转换成1,第二个数字转换成2,等等。。你知道吗

x = "5512"
function = {}
count = 1
output = ""

for digit in x:
     if digit in function:
         output += function[digit]
     else:
         function[digit] = str(count)
         count += 1
         output += function[digit]

print(output)
#Outputs 1123 (5->1, 1->2, 2->3)

相关问题 更多 >