Skip to main content
 首页 » 编程设计

python之比较python中的两个变量列表

2024年10月01日8java哥

我在 python 中有两个包含元素的列表。我想在这两个列表中执行一些检查。我的 list 如下:

list_A = [["'EASY'", "'LEVEL_C'", "'4'", '0.714', '\n'], ["'EASY'", "'LEVEL_D'", "'5'", '0.778', '\n'], ["'EASY'", "'LEVEL_D'", "'5'", '0.226', '\n'], ["'EASY'", "'LEVEL_D'", "'5'", '0.222', '\n'], ...] 
list_B = [["'EASY'", "'LEVEL_B'", "'2'", '1.000', '\n'], ["'EASY'", "'LEVEL_C'", "'3'", '1.000', '\n'], ["'EASY'", "'LEVEL_D'", "'4'", '1.000', '\n'], ["'EASY'", "'LEVEL_D'", "'4'", '0.290', '\n'], ...] 

对于变量“EASY”和取值 (LEVEL_A - LEVEL_F) 的变量级别,第三个变量对应于分数 (1-6) 和置信度变量 (0-1)。我想要做的是比较变量 easy 和 level 的两个列表,并在所有情况下查找两个列表(list_A 和 list_B)中哪个具有更高的分数以及哪个置信度。我该怎么做?

我构建规则的方式是,一开始我从可执行文件中获取行并将它们过滤到列表中。我的列表的矢量示例如下:

Rule: ('EASY', 'LEVEL_E') ==> ('4') , 0.182  
'EASY' 'LEVEL_E' '4'  0.182  
["'EASY'",  "'LEVEL_E'", , "'4'", '0.182', '\n'] 

以及我用来创建矢量的代码:

 for row in my_lines: 
   print row 
   row = re.sub('[()]', "", row) 
   row = row.replace("Rule: ", "") 
   row = row.replace(",", "") 
   row = row.replace("==>", "") 
   print row 
   split = re.split(r' +', row) 
   print split 

然后,一旦我创建了我的列表,我就会用对应于变量 Level 的第二个元素对它们进行排序:

list_A.sort(key=lambda x: x[1]) 
list_B.sort(key=lambda x: x[1]) 

编辑: 我已经用可变级别对列表进行了排序。现在我想比较关于所有变量级别分数的两个列表。当一个级别不存在时,分数为零,当相同分数存在两次时,系统应该选择具有最高置信度的分数。如何比较变量级别的所有可能值?

请您参考如下方法:

这只是部分答案,但将数据放在一个字典中会更令人愉快:

dict_a = { 
    'LEVEL_D': {'difficulty': 'EASY', 'score': 1, 'confidence': 0.778}, 
    'LEVEL_F': {'difficulty': 'EASY', 'score': 6, 'confidence': 0.750}, 
    'LEVEL_C': {'difficulty': 'EASY', 'score': 7, 'confidence': 0.714}, 
    } 
 
dict_b = { 
    'LEVEL_F': {'difficulty': 'EASY', 'score': 8, 'confidence': 0.800}, 
    'LEVEL_B': {'difficulty': 'EASY', 'score': 2, 'confidence': 0.900}, 
    'LEVEL_D': {'difficulty': 'EASY', 'score': 3, 'confidence': 1.000}, 
    } 

然后您可以编写一个简单的 for 循环来获取内部字典的所需值:

for level in dict_a: 
    if level in dict_b: 
        stats_a = dict_a[level] 
        stats_b = dict_b[level] 
        score_a = stats_a['score'] 
        score_b = stats_b['score'] 
        conf_a = stats_a['confidence'] 
        conf_b = stats_b['confidence'] 
        print(level, score_a, score_b, conf_a, conf_b) 

我们需要弄清楚如何以这种方式重新排列数据。列表列表方法实际上也可以工作,但效率较低。主要问题是数据排序不正确。

编辑:要获取特定级别得分较高的列表名称,您可以这样做:

for level in dict_a: 
    if level in dict_b: 
        stats_a = dict_a[level] 
        stats_b = dict_b[level] 
        container = 'A' if stats_a['score'] > stats_b['score'] else 'B' 
        print('Container {} has the higher score for level {}.'.format(container, level))