📜  使用 Dictionary Get() 方法在Python中组合相似字符

📅  最后修改于: 2022-05-13 01:54:27.453000             🧑  作者: Mango

使用 Dictionary Get() 方法在Python中组合相似字符

让我们看看如何在一个列表中组合相似的字符。

例子 :

我们将使用字典类的 get() 方法。

字典.get()

get() 方法返回具有指定键的项的值。

算法 :

  1. 宣布清单。
  2. 声明字典。
  3. 使用 get() 方法遍历列表,如果找到新键,则为其分配值 0,并添加 1 使最终值 1。否则,如果键重复,则将 1 添加到之前计算的值。这样,现在每个键都有一个分配的值,并且记录了所有字符的频率。
  4. 分离所有键和值并将它们存储在 2 个不同的列表中。
  5. 使用 zip()函数将键的乘积及其各自的值存储在结果列表中。
  6. 显示结果。

示例 1:

python3
# declaring the list of characters
mylist = ['g', 'e', 'e', 'k', 's', 'f',
          'o', 'r', 'g', 'e', 'e', 'k', 's']
 
# declaring the dictionary
dictionary = {}
 
# counting the frequency of the keys
for key in mylist:
    dictionary[key] = dictionary.get(key, 0) + 1
 
# storing the of keys and values
k = list(dictionary.keys())
v = list(dictionary.values())
 
# declaring the result list
result = []
 
# storing the product of keys and
# their respective values in result
for i, j in zip(k, v):
    result.append(i * j)
     
# displaying the result
print(result)


python3
# declaring the list of characters
mylist = ['p', 'y', 't', 'h', 'o', 'n', 't',
          'u', 't', 'o', 'r', 'i', 'a', 'l']
 
# declaring the dictionary
dictionary = {}
 
# counting the frequency of the keys
for key in mylist:
    dictionary[key] = dictionary.get(key, 0) + 1
 
# storing the of keys and values
k = list(dictionary.keys())
v = list(dictionary.values())
 
# declaring the result list
result = []
 
# storing the product of keys and
# their respective values in result
for i, j in zip(k, v):
    result.append(i * j)
     
# displaying the result
print(result)


输出 :

['gg', 'eeee', 'kk', 'ss', 'f', 'o', 'r']

示例 2:

蟒蛇3

# declaring the list of characters
mylist = ['p', 'y', 't', 'h', 'o', 'n', 't',
          'u', 't', 'o', 'r', 'i', 'a', 'l']
 
# declaring the dictionary
dictionary = {}
 
# counting the frequency of the keys
for key in mylist:
    dictionary[key] = dictionary.get(key, 0) + 1
 
# storing the of keys and values
k = list(dictionary.keys())
v = list(dictionary.values())
 
# declaring the result list
result = []
 
# storing the product of keys and
# their respective values in result
for i, j in zip(k, v):
    result.append(i * j)
     
# displaying the result
print(result)

输出 :

['a', 'h', 'i', 'l', 'n', 'oo', 'p', 'r', 'ttt', 'u', 'y']