比较两个列表时循环的Python问题

2024-05-18 23:59:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个小问题,我试图比较两个列表中的单词,以建立一个相似的百分比,但这里是一件事,如果我有相同的单词在每个列表中2次,我得到一个错误的百分比。你知道吗

首先我做了一个小剧本:

data1 = ['test', 'super', 'class', 'test', 'boom']
data2 = ['test', 'super', 'class', 'test', 'boom']
res = 0
nb = (len(data1) + len(data2)) / 2
if data1 and data2 and nb != 0:
    for id1, item1 in enumerate(data1):
        for id2, item2 in enumerate(data2):
            if item1 == item2:
                res += 1 - abs(id1 - id2) / nb
    print(res / nb * 100)

问题是,如果我有两次相同的词在列表中的百分比将大于100%。 为了解决这个问题,我在'res+=1-abs(id1-id2)/nb'后面加了一个'break',但是这个百分比仍然是假的。你知道吗

希望你能理解我的问题,谢谢你的帮助!你知道吗


Tags: test列表lenifres单词class百分比
3条回答
data1 = ['test', 'super', 'class', 'test', 'boom']
data2 = ['test', 'super', 'class', 'test', 'boom']
from collections import defaultdict

dic1 =defaultdict(int)
dic2=defaultdict(int)

for i in data1:
    dic1[i]+=1

for i in data2:
    dic2[i]+=1

count = 0

for i in dic1:
    if i in dic2.keys():
        count+=abs(dic2[i]-dic1[i])


result =( (1-count/(len(data1)+len(data2))) *100)

输出

100.0

您可以使用difflib.SequenceMatcher来比较两个列表的相似性。试试这个:

from difflib import SequenceMatcher as sm
data1 = ['test', 'super', 'class', 'test', 'boom']
data2 = ['test', 'super', 'class', 'test', 'boom']
matching_percentage = sm(None, data1, data2).ratio() * 100

输出

100.0

请尝试以下代码:

data1 = ['test', 'super', 'class', 'class', 'test', 'boom']
data2 = ['test', 'super', 'class', 'class', 'test', 'boom']
res = 0
nb = (len(data1) + len(data2)) / 2.0

def pos_iter(index, sz):
    yield index
    i1 = index - 1
    i2 = index + 1
    while i1 >=0 and i2 < sz:
        if i1 >= 0:
            yield i1
            i1 -=1
        if i2 < sz:
            yield i2
            i2 += 1
if data1 and data2 and nb != 0:
    for id1, item1 in enumerate(data1):
        for id2 in pos_iter(id1, len(data2)):
            item2 = data2[id2]
            if item1 == item2:
                res += max(0, 1 - abs(id1 - id2) / nb)
                break
    print(res / nb * 100)

代码的问题是,总是从头开始在第二个data2中查找匹配的单词。如果单词重复,会给出无效值。你需要一直在data1中搜索单词的“around”位置,因为你想找到最近的一个。你知道吗

此外,你需要打破你已经添加,否则与所有相同的文字将走到1.0以上的方式。您的nb变量需要是double(否则python2将舍入除法结果)。您应该确保1 - abs(id1 - id2) / nb大于零,因此我添加了max(0, ...)。你知道吗

相关问题 更多 >

    热门问题