Python - 连接动态频率
给定元素列表,动态执行频率连接,即每个元素与其频率连接,直到其索引。
Input : test_list = [‘z’, ‘z’, ‘e’, ‘f’, ‘f’]
Output : [‘1z’, ‘2z’, ‘1e’, ‘1f’, ‘2f’]
Explanation : As occurrence increase, concat number is increased.
Input : test_list = [‘g’, ‘f’, ‘g’]
Output : [‘1g’, ‘1f’, ‘2g’]
Explanation : As occurrence increase, concat number is increased.
方法:使用 defaultdict() + “+”运算符+ str()
在这种情况下,动态频率计算是使用 defaultdict() 完成的,而 str() 用于使用“+”运算符将元素转换为字符串以进行有效连接。
Python3
# Python3 code to demonstrate working of
# Concatenate Dynamic Frequency
# Using defaultdict() + "+" operator + str()
from collections import defaultdict
# initializing list
test_list = ['z', 'z', 'e', 'f', 'f', 'e', 'f', 'z', 'c']
# printing original list
print("The original list is : " + str(test_list))
memo = defaultdict(int)
res = []
for ele in test_list:
memo[ele] += 1
# adding Frequency with element
res.append(str(memo[ele]) + str(ele))
# printing result
print("Dynamic Frequency list : " + str(res))
输出
The original list is : ['z', 'z', 'e', 'f', 'f', 'e', 'f', 'z', 'c']
Dynamic Frequency list : ['1z', '2z', '1e', '1f', '2f', '2e', '3f', '3z', '1c']