簡體   English   中英

計算 python dict 中的相等值(沖突)

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM