Я использую Python 2.7. Я пытаюсь сравнить элементы значения в словаре.
У меня две проблемы. Во-первых, это итерация значений в словаре с длиной 1. Я всегда получаю сообщение об ошибке, потому что python не выполняет итерацию целых чисел, а один элемент в качестве значения является целым числом для python. Я попытался изменить элемент на строку. Я попытался изменить весь словарь на строку. В этих случаях итерация также сравнивает запятые и скобки, и это не цель. Поэтому я продублировал статью. Значения в key:1 и key:4 являются одним и тем же элементом два раза. Это решение работает, но, естественно, немного меняет результаты.
Вторая проблема заключается в том, что подсчет матчей работает некорректно. Да, из-за первой проблемы, но есть еще одна. Мой код сравнивает все элементы значений со всеми другими элементами значений в словаре. Одинаковые модули не сравниваются. Если в сравнении есть одно совпадение, проблем нет. Но если в сравнении было два совпадения, код выведет результат два раза как одно совпадение. Но мне нужен только один результат с двумя совпадениями. Код содержит много комментариев, поэтому я надеюсь, что вы его понимаете.
#dicModul is a dictionary with the modulnames(keys of dictionary) and the components of the modul(value of dictionary).
# If a modul consists of one component, it is impossible to iterate the modul, therefore this component is two times in a modul.
# Any ideas how to iterate a single value item in a dictionary?
dicModul = {0:(0,1),1:(1,1), 2:(2,3,4,5,6,1,7,2),
3:(8,1),4:(9,9), 5:(10,10,5,11,0,12,13), 6:(10,11,9,7)}
#The list is needed for the iteration and to operate the different modul in the dictionary by following for loops.
ModulList = [0,1,2,3,4,5,6]
#Counter is needed for counting same components in different moduls.
Counter = 0
for modKey in ModulList: #For-loop is needed for iteration of keys
for modKey2 in ModulList: #2nd for-loop of Modulkeys.The components of moduls have to be checked for matches in other moduls.
#Therefore a second iteration of the modul list is needed.
if modKey == modKey2: #Same moduls do not have to be checked.
print "Skip same Moduls"
Counter = 0 #The modkey2 have to changed by iteration. The counter have to be reset.
elif modKey != modKey2: #Different moduls have to be checked.
for modVal in dicModul[modKey]: #Iteration of components for iterated modul.
if modVal in dicModul[modKey2]: #Checking iterated components in different modul
Counter = Counter + 1 #If component was in different moduls, counter will add +1
print "Modul: "+str(modKey)+" % Modul: "+str(modKey2)+ " Matches= "+str(Counter)
#print function for both moduls and number of same components
Counter =0
Я думаю, что если на этом этапе можно разделить предыдущий проверенный ключ и проверенный ключ, счетчик не будет начинаться с 0 каждый раз. Я пытался решить проблему и искать решения, но не нашел этого случая.
цикл по словарю (предыдущие значения) python
Как получить доступ к предыдущему/следующему элементу во время цикла?
Думаю, решение должно выглядеть как следующий код.
Я помечаю свое предложение знаком #->
#dicModul is a dictionary with the modulnames(keys of dictionary) and the components of the modul(value of dictionary).
# If a modul consists of one component, it is impossible to iterate the modul, therefore this component is two times in a modul.
# Any ideas how to iterate a single value item in a dictionary?
dicModul = {0:(0,1),1:(1,1), 2:(2,3,4,5,6,1,7,2),
3:(8,1),4:(9,9), 5:(10,10,5,11,0,12,13), 6:(10,11,9,7)}
#The list is needed for the iteration and to operate the different modul in the dictionary by following for loops.
ModulList = [0,1,2,3,4,5,6]
#Counter is needed for counting same components in different moduls.
Counter = 0
for modKey in ModulList: #For-loop is needed for iteration of keys
for modKey2 in ModulList: #2nd for-loop of Modulkeys.The components of moduls have to be checked for matches in other moduls.
#Therefore a second iteration of the modul list is needed.
if modKey == modKey2: #Same moduls do not have to be checked.
print "Skip same Moduls"
Counter = 0 #The modkey2 have to changed by iteration. The counter have to be reset
elif modKey != modKey2: #Different moduls have to be checked.
for modVal in dicModul[modKey]: #Iteration of components for iterated modul.
if modVal in dicModul[modKey2]: #Checking iterated components in different modul
#-> if modKey2 == previous modKey2: #Checking if is the previous modul, so counter is not reset.
#-> Counter = Counter +1
#-> print "Modul: "+str(modKey)+" % Modul: "+str(modKey2)+ " Matches= "+str(Counter)
#-> else:
#-> Counter = 1 #Counter is setted 1, because a same component is found in a different modul.
elif:
Counter = 0
Это мое ожидаемое решение
Modul Modul Matches
skip same modul
0 1 1
0 2 1
0 3 1
0 4 0
0 5 1
skip same modul
1 2 1
1 3 1
1 4 0
1 5 0
skip same modul
2 3 1
2 4 0
2 5 1
2 6 1
skip same modul
3 4 0
3 5 0
skip same modul
4 5 0
4 6 1
skip same modul
5 6 3