使用 Dictionary Get() 方法在Python中组合相似字符
让我们看看如何在一个列表中组合相似的字符。
例子 :
Input : [‘g’, ‘e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘g’, ‘e’, ‘e’, ‘k’, ‘s’]
Output : [‘gg’, ‘eeee’, ‘kk’, ‘ss’, ‘f’, ‘o’, ‘r’]
我们将使用字典类的 get() 方法。
字典.get()
get() 方法返回具有指定键的项的值。
Syntax : dictionary.get(key name, value)
Parameters :
- keyname : The key name of the dictionary item.
- value : (Optional) If the specified key does not exist, then a value is returned.
Returns : Value of the item with the specified key
算法 :
- 宣布清单。
- 声明字典。
- 使用 get() 方法遍历列表,如果找到新键,则为其分配值 0,并添加 1 使最终值 1。否则,如果键重复,则将 1 添加到之前计算的值。这样,现在每个键都有一个分配的值,并且记录了所有字符的频率。
- 分离所有键和值并将它们存储在 2 个不同的列表中。
- 使用 zip()函数将键的乘积及其各自的值存储在结果列表中。
- 显示结果。
示例 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']