比较字典中的价值项目和计数匹配 [英] Comparison of value items in a dictionary and counting matches

查看:192
本文介绍了比较字典中的价值项目和计数匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Python 2.7。
我试图比较字典中的值项。



我有两个问题。
首先是长度为1的字典中的值的迭代。我总是得到一个错误,因为python不会迭代整数和单个项目,因为值是python的整数。
我试图将项目更改为一个字符串。我试图把整个字典改成字符串。在这些情况下,迭代比较逗号和括号,而那不是目的。所以我重复了这个项目。 key:1和key:4中的值是同一个项目,两次。这种解决方案的工作,但它自然会改变一点点结果。



第二个问题是计数匹配不能正常工作。
是的,因为第一个问题,但还有一个。
我的代码将所有值项目与字典中的所有其他值项目进行比较。相同的模块不会被比较。如果有一个比较匹配,没有问题。
但是如果一个比较有两个匹配,那么这个代码就会输出两个匹配的结果。但我只想要一个结果,有两场比赛。
代码中包含很多注释,所以我希望你可以把它打出来。

  #dicModul是一个模块名(字典的键)和模块的组件(字典的值)。 
#如果模块由一个组件组成,则不可能迭代模块,因此这个组件在模块中是两次。
#任何想法如何迭代字典中的单个值项目?
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)}
#是迭代所需要的,并通过跟随for循环来操作字典中的不同模块。
ModulList = [0,1,2,3,4,5,6]
#Counter用于计算不同模块中的相同分量。
Counter = 0
ModulList中的modKey:#For循环需要迭代密钥
用于ModulList中的modKey2:#Modulkeys的第2个for循环。模块的组成部分必须是检查其他模块中的匹配。
#因此需要模块列表的第二次迭代。
如果modKey == modKey2:#同样的模式不需要被检查。
打印跳过相同的模块
计数器= 0#modkey2必须通过迭代来改变。计数器必须重置。
elif modKey!= modKey2:#必须检查不同的模块。
用于dicModul [modKey]中的modVal:#迭代模块的组件迭代。
如果modVal在dicModul [modKey2]中:#检查不同模块中的迭代组件b $ b Counter = Counter + 1#如果组件处于不同的模块中,counter将添加+1
printModul: + str(modKey)+%Modul:+ str(modKey2)+Matches =+ str(计数器)
两个模块和相同元件数量的print函数
计数器= 0

我想,如果在此关键点之前的选中键和选中的键之间可以分隔,每次都从0开始。
我试图解决问题并寻找解决方案,但是我没有发现这种情况。

循环上字典(以前的值)python



如何访问上一个/下一个元素while循环?

计算词典中的项目



我想解决方案必须看起来像下一个代码。

我用#标记我的建议 - >

  #dicModul是一个模块名称为字典键)和模块的组件(字典的值)。 
#如果模块由一个组件组成,则不可能迭代模块,因此这个组件在模块中是两次。
#任何想法如何迭代字典中的单个值项目?
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)}
#是迭代所需要的,并通过跟随for循环来操作字典中的不同模块。
ModulList = [0,1,2,3,4,5,6]
#Counter用于计算不同模块中的相同分量。
Counter = 0
ModulList中的modKey:#For循环需要迭代密钥
用于ModulList中的modKey2:#Modulkeys的第2个for循环。模块的组成部分必须是检查其他模块中的匹配。
#因此需要模块列表的第二次迭代。
如果modKey == modKey2:#同样的模式不需要被检查。
打印跳过相同的模块
计数器= 0#modkey2必须通过迭代来改变。计数器必须被重置
elif modKey!= modKey2:#必须检查不同的模块。
用于dicModul [modKey]中的modVal:#迭代模块的组件迭代。
如果在dicModul中使用了modVal [modKey2]:#检查不同模块中的迭代组件
# - >如果modKey2 ==上一个modKey2:#检查如果是以前的模块,所以计数器不复位。
# - > Counter = Counter +1
# - > (modKey)+%Modul:+ str(modKey2)+Matches =+ str(Counter)
# - > else:
# - > Counter = 1 #Counter设置为1,因为在不同的模块中找到了相同的组件。
elif:
Counter = 0

这是我期望的解决方案

 模块模块匹配
跳过相同的模块
0 1 1
0 2 1
0 3 1
0 4 0
0 5 1
跳过相同的模块
1 2 1
1 3 1
1 4 0
1 5 0
跳过相同的模块
2 3 1
2 4 0
2 5 1
2 6 1
跳过相同的模块
3 4 0
3 5 0
跳过相同的模块
4 5 0
4 6 1
跳过相同的模块
5 6 3


解决方案

我建议你看看 $ c>循环,以及它们如何工作。 Codeacademy 是一个伟大的(免费)互动资源。我不是100%确定的,我明白你在问什么,所以我主要是从你的问题题目。我想我明白你想要做什么,但是如果我这样做的话,那么对自己来说真的很难。

迭代包含单个项目的字典:

  dicty = {'a':1} 
for key in dicty:
print key

在字典中迭代值和键:

打印键
打印val
对于key而言,

 ,val在dicty.iteritems 



相当于:

 东西:
val =东西[键]
打印键
打印val



计数(键)在两个字符匹配:

  count = 0 
keys_counted = []

dicty_a = {'key1':'val1','key2':'val2'}
dicty_b = {'key1':'val1','keyB':'valB'}
为keyA,val在dicty_a.iteritems()中为:
为keyB,valB为dicty_b.iteritems():
如果keyB == keyA和keyA不在keys_counted中:
count + = 1
keys_counted.append(valA)

确保不重复检查的最常见解决方案是构建一个列表,检查它,然后在最后抛出。例如:

  list_printed = [] 
代表范围(5)中的x:
代表y范围(5):
如果[x,y]不在list_printed中:
print x,y
list_printed.append([y,x])


  0 0 $ b   
$ b> $ b 0 1
0 2
0 3
0 4
1 1
1 2
1 3
1 4
2 2
2 3
2 4
3 3
3 4
4 4


$ b

Enumerate()可让您获取字典中的项目键和值,或迭代次数和值,如果你正在循环一个列表。



关于遍历单个项目的问题。 元组很奇怪,特别是单项。你需要尾随的逗号,或者它不是一个元组,它是一个int。老实说,这是一个错误,而不是一个功能,但乐观地说,这可能是一些计算机科学的原因超出我的薪酬水平的重要。此外,区分列表 [] 和元组()的重要因素是元组是不可变的。在这种情况下你可能不需要使用元组。话虽如此,你只是因为,你说错了,你不能迭代一个整数:
$ b $ pre $ lo $ 1)
for x in loopy:
print x#这将不会引发错误

loopy =(1)
for loopy:
print x#this _will_ raise a error

loopy = [1]
for x in loopy:
print x#this will _not_ raise an error

b loopy = 1
for loopy:
print x#this _will_ raise an error

将其应用于您要做的事情

  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)}

keys_checked = []

$ t






$ b stuff = [x,y]
如果stuff不在matching_list和x == y中:
计数器+ = 1
matched_list.append(stuff)
返回计数器

for key_outerloop,val_outerloop in dicModul.iteritems():
for key_innerloop,val_innerloop in dicModul。 iteritems():
如果key_outerloop == key_innerloop:
printskip ...
elif [key_innerloop,key_outerloop]不在keys_checked中:
matches = get_tuple_matches(val_outerloop,val_innerloop )
keys_checked.append([key_outerloop,key_innerloop])
printModul:+ str(key_outerloop)+| Modul:+ str(key_innerloop)+|输出:

$ b b

 跳过... 
模块:0 |模块:1 |匹配= 1
模块:0 |模块:2 |匹配= 1
模块:0 |模块:3 |匹配= 1
模块:0 |模块:4 |匹配= 0
模块:0 |模块:5 |匹配= 1
模块:0 |模块:6 |匹配= 0
跳过...
模块:1 |模块:2 |匹配= 1
模块:1 |模块:3 |匹配= 1
模块:1 |模块:4 |匹配= 0
模块:1 |模块:5 |匹配= 0
模块:1 |模块:6 |匹配= 0
跳过...
模块:2 |模块:3 |匹配= 1
模块:2 |模块:4 |匹配= 0
模块:2 |模块:5 |匹配= 1
模块:2 |模块:6 |匹配= 1
跳过...
模块:3 |模块:4 |匹配= 0
模块:3 |模块:5 |匹配= 0
模块:3 |模块:6 |匹配= 0
跳过...
模块:4 |模块:5 |匹配= 0
模块:4 |模块:6 |匹配= 1
跳过...
模块:5 |模块:6 |匹配= 2
跳过...

code


Im using Python 2.7. Im trying to compare the value items in a dictionary.

I have two problems. First is the iteration of values in a dictionary with a length of 1. I always get an error, because python doesn't iterate integer and a single item as value is an integer for python. I have tried to change the item to a string. I have tried to change the whole dictionary to string. In these cases the iteration compares commas and brackets, as well and thats not the purpose. Therefore I duplicated the item. The values in key:1 and key:4 are one and the same item, two times. This solution works, but it changes a little bit the results, naturally.

The second problem is that the counting of matches doesn't work correctly. Yes, because of the first problem, but there is another one. My code compares all value items, with all other value items in the dictionary. Same moduls are not compared. If there is one match in a comparison, there is no problem. But if a comparison had two matches, the code will outputs the result two times as one match. But I want just one result, with two matches. The code includes many comments, so I hope you can unterstand it.

    #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

I think, if the can separte between the previous checked key and checked key at this juncture, the counter will not start at 0, every time. I tried to solve the problem and search for solutions, but I didn`t found this case.

loop on a dictionary (previous values) python

How to access previous/next element while for looping?

Count items in dictionary

I guess the solution have to look like the next code.
I mark my suggestion with #->

#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

This is my expected solution

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

解决方案

I would recommend you take a look at for loops, and how they work. Codeacademy is a great (free) interactive resource. I'm not 100% sure I understand what you're asking, so I'm mainly going off of your question title. I think I understand what you're trying to do, but if I do, you're making it really difficult on yourself.

Iterating a dictionary with a single item:

dicty = {'a': 1}    
for key in dicty:
    print key

Iterating through values and keys in dictionaries:

for key, val in dicty.iteritems():
    print key
    print val

which is equivalent to:

for key in stuff:
    val = stuff[key]
    print key
    print val

Counting (key) matches in two dicts:

count = 0
keys_counted = []

dicty_a = {'key1': 'val1', 'key2': 'val2'}
dicty_b = {'key1': 'val1', 'keyB': 'valB'}
for keyA, valA in dicty_a.iteritems():
    for keyB, valB in dicty_b.iteritems():
        if keyB == keyA and keyA not in keys_counted:
            count += 1
            keys_counted.append(valA)

The most common solution to making sure you don't duplicate a check is to build a list, check against it, then throw it out at the end. For example:

list_printed = []
for x in range(5):
    for y in range(5):
        if [x, y] not in list_printed:
            print x, y
            list_printed.append([y,x])

outputs:

0 0
0 1
0 2
0 3
0 4
1 1
1 2
1 3
1 4
2 2
2 3
2 4
3 3
3 4
4 4

Enumerate() allows you to get both the keys and values of items in your dictionary, or the iteration number and value if you are looping through a list.

With regard to your issue with iterating over single items. Tuples are weird, especially with single items. You need the trailing comma or it's not a tuple, it's an int. Honestly, that strikes me as a bug, not a feature, but optimistically, it's probably important for some computer-sciency reason that's way beyond my paygrade. Also, the big thing that distinguishes lists [] and tuples () is that tuples are immutable. You probably don't need to be using tuples in this case. Having said that, you were getting your error just because, you said, you can't iterate an integer:

loopy = (1,)
for x in loopy:
    print x # this will _not_ raise an error

loopy = (1)
for x in loopy:
    print x # this _will_ raise an error

loopy = [1]
for x in loopy:
    print x # this will _not_ raise an error

loopy = 1
for x in loopy:
    print x # this _will_ raise an error

Applying this to what you're trying to do:

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)}

keys_checked = []

def get_tuple_matches(t1, t2):
    counter = 0
    matched_list = []
    for x in t1:
        for y in t2:
            stuff = [x, y]
            if stuff not in matched_list and x == y:
                counter +=1
                matched_list.append(stuff)
    return counter

for key_outerloop, val_outerloop in dicModul.iteritems():
    for key_innerloop, val_innerloop in dicModul.iteritems():
        if key_outerloop == key_innerloop:
            print "skip..."
        elif [key_innerloop, key_outerloop] not in keys_checked:
            matches = get_tuple_matches(val_outerloop, val_innerloop)
            keys_checked.append([key_outerloop, key_innerloop])
            print "Modul: " + str(key_outerloop) + " | Modul: " + str(key_innerloop) + " | Matches= "+ str(matches)

output:

skip...
Modul: 0 | Modul: 1 | Matches= 1
Modul: 0 | Modul: 2 | Matches= 1
Modul: 0 | Modul: 3 | Matches= 1
Modul: 0 | Modul: 4 | Matches= 0
Modul: 0 | Modul: 5 | Matches= 1
Modul: 0 | Modul: 6 | Matches= 0
skip...
Modul: 1 | Modul: 2 | Matches= 1
Modul: 1 | Modul: 3 | Matches= 1
Modul: 1 | Modul: 4 | Matches= 0
Modul: 1 | Modul: 5 | Matches= 0
Modul: 1 | Modul: 6 | Matches= 0
skip...
Modul: 2 | Modul: 3 | Matches= 1
Modul: 2 | Modul: 4 | Matches= 0
Modul: 2 | Modul: 5 | Matches= 1
Modul: 2 | Modul: 6 | Matches= 1
skip...
Modul: 3 | Modul: 4 | Matches= 0
Modul: 3 | Modul: 5 | Matches= 0
Modul: 3 | Modul: 6 | Matches= 0
skip...
Modul: 4 | Modul: 5 | Matches= 0
Modul: 4 | Modul: 6 | Matches= 1
skip...
Modul: 5 | Modul: 6 | Matches= 2
skip...

code

这篇关于比较字典中的价值项目和计数匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆