Python中字典的连接操作

2024-09-29 02:17:24 发布

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

第一步。i/p=“wwaaadexxxxxx”

第二步。转换={'w':4,'a':3,'d':1,'e':1,'x':6}

最后一步。o/p='w4a3d1e1x6'

我在S2,怎么走到最后一步

如能直接转换1->;决赛

时间复杂度应较低,但如有任何解决方案,将不胜感激

我想以存储在任何变量中的字符串形式返回

不进口任何东西


Tags: 字符串gt时间解决方案复杂度形式s2决赛
3条回答

您可以使用^{}

from itertools import groupby

ip = "wwwwaaadexxxxxx"
op = "".join(f"{k}{len(list(g))}" for k, g in groupby(ip))
# 'w4a3d1e1x6'

您可以使用理解(但需要将这些数字转换为字符串),请尝试以下代码:

converted = {'w': 4, 'a': 3, 'd': 1, 'e': 1, 'x': 6}
print("".join([str(char) for k, v in converted.items() for char in (k, v)]))

使用计数器

from collections import Counter
ip= "wwwwaaadexxxxxx"

print(''.join([i+str(x) for i, x in Counter(ip).items()]))

#'w4a3d1e1x6'

相关问题 更多 >