我想在python中構建一個函數,該函數產生兩個字典的值,如果dict1
的特定值匹配dict2
的特定值。我的功能看起來是這樣的:幫助在元組匹配Python函數中使用* args
def dict_matcher(dict1, dict2, item1_pos, item2_pos):
"""Uses a tuple value from dict1 to search for a matching tuple value in dict2. If a match is found, the other values from dict1 and dict2 are returned."""
for item1 in dict1:
for item2 in dict2:
if dict1[item1][item1_pos] == dict2[item2][item2_pos]:
yield(dict1[item1][2], dict2[item2][6])
我使用dict_matcher
這樣的:
matches = [myresults for myresults in dict_matcher(dict1, dict2 , 2, 6)]
print(matches)
當我打印matches
我得到這樣正確地匹配dict1和dict2值的列表:
[('frog', 'frog'), ('spider', 'spider'), ('cricket', 'cricket'), ('hampster', 'hampster')]
如何向此函數添加可變參數,以便除了打印每個d的匹配值ictionary,我還可以在dict1[item1][2] and dict2[item2][6]
匹配的情況下打印每個字典項目的其他值?我可以使用*參數嗎?謝謝您的幫助。
編輯: 好吧,似乎有一些混淆,我試圖做什麼讓我嘗試另一個例子。
dict1 = {1: ('frog', 'green'), 2: ('spider', 'blue'), 3: ('cricket', 'red')}
dict2 = {a: ('frog', 12.34), b: ('ape', 22.33), c: ('lemur', 90.21)}
dict_matcher(dict1, dict2, 0, 0)
會發現[0]從dict2 dict1和值[0]的值匹配的值。在這種情況下,唯一的比賽是'青蛙'。我上面的功能是這樣做的。我想要做的是擴展功能,以便能夠打印出我想要在函數參數中指定的dict1[value][0] == dict2[value][0]
字典項目中的其他值。
也許我只是愚蠢,但你的問題似乎混淆。值2和6在調用中用於item1_pos和item2_pos(args爲空),但它們看起來好像是後來的args(以某種奇怪的方式對我來說毫無意義)。 –
@andrewcooke對不起,我發現它很混亂。我更新了我的問題,所以我希望現在更清楚。 – drbunsen
嗯。在初始代碼塊中它是否也應該是'yield(dict1 [item1] [item1_pos],dict2 [item2] [item2_pos])' –