我使用的是python2.7。 我在试着比较字典里的值项。在
我有两个问题。 首先是字典中长度为1的值的迭代。我总是得到一个错误,因为python不迭代整数,对于python来说,作为值的单个项是一个整数。 我试着把这个项目改成一个字符串。我试图把整本词典改成字符串。在这些情况下,迭代还比较逗号和方括号,这不是目的。所以我复制了这个项目。中的值键:1和钥匙: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开始。 我试图解决这个问题并寻找解决办法,但我没有找到这个案子。在
loop on a dictionary (previous values) python
How to access previous/next element while for looping?
我想解决方案必须看起来像下一个代码。
我用#->
这是我期望的解决方案
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
我建议您看看
for
循环,以及它们是如何工作的。Codeacademy是一个很棒的(免费)交互式资源。我不能百分之百地肯定我能理解你的问题,所以我把你的问题标题去掉。我想我理解你想做什么,但如果我这么做了,你就给自己带来了很大的困难。在迭代使用单个项目的字典:
迭代字典中的值和键:
^{pr2}$相当于:
在两个dict中计算(键)匹配:
确保你不重复检查的最常见的方法是建立一个列表,对照它进行检查,然后在最后扔掉它。例如:
输出:
Enumerate()
允许您同时获取字典中项目的键和值,或者,如果您在列表中循环,则可以获取迭代次数和值。在关于您的迭代单个项目的问题。Tuples are weird,尤其是单个项目。你需要尾随的逗号,或者它不是元组,而是一个整数。老实说,这让我觉得是一个bug,不是一个特性,但乐观地说,它可能对某些计算机科学很重要,这远远超出了我的工资级别。另外,区别列表
[]
和元组()
的一个重要区别是元组是不可变的。在这种情况下,您可能不需要使用元组。话虽如此,你得到的错误仅仅是因为,你说,你不能迭代一个整数:将这一点应用到您要做的事情上:
输出:
code
相关问题 更多 >
编程相关推荐