[英]Counting equal values(collision) in python dict
這篇文章對我沒有用post_link
所以我在這里問:
我有一個 python 字典:
a = {'Andres':234,'Paul':345,'Andres':675}
我有這段代碼
def get_index(dict, a_string):
# Variable to store the result (updated after each iteration)
result = 0
#Variable to append the final result of each key in the dict
collisions =[]
for a_character in a_string:
# Convert the character to a number (using ord)
a_number = ord(a_character)
# Update result by adding the number
result += a_number
collisions.append(result)
# Take the remainder of the result with the size of the data list
list_index = result % len(data_list)
return collisions
返回字符串的 unicode,例如:
get_index(teste, 'Andres')
returns [605]
我想要的是為每個鍵傳遞我的字典,值代碼計算每個字符串的 de unicode_sum 和 append 到碰撞:
我試過了:
def get_index(dict):
for k,v in teste.items:
for a_character in a_string:
# Convert the character to a number (using ord)
a_number = ord(a_character)
# Update result by adding the number
result += a_number
collisions.append(result)
我想要得到的結果是:
get_index(a)
output: [605, 402, 605]
然后我可以通過執行len(collision) - set(collision)
來計算碰撞次數
由於"Andres"
不能在您的字典中出現兩次,我將打亂另一個實例的字母以表明您將獲得605
的兩個結果:
>>> d = {"Andres": 234, "Paul": 345, "nAsedr": 675}
>>> collisions = [sum(map(ord, s)) for s in d]
>>> collisions
[605, 402, 605]
>>> len(collisions) - len(set(collisions))
1
這也適用於字符串list
、字符串tuple
和一set
字符串(其中一set
也不允許您擁有多個"Andres"
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.