如何按给定索引的项目过滤元组列表并将其转换为列表字典 [英] How to filter a list of tuples by items at given index and convert them into a dictionary of lists

查看:96
本文介绍了如何按给定索引的项目过滤元组列表并将其转换为列表字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下列表:

Lista = [('amazon', 'Amazon', 1.0), 
         ('amazon', 'Alexa', 0.8), 
         ('amazon', 'microsoft', 0.6), 
         ('amazon', 'Amazon Pay', 0.7), 
         ('amazon', 'Prime', 0.4),
         ('alien', 'jack' , 0.0), 
         ('alien', 'dell', 0.6),
         ('alien', 'apple', 0.0),
         ('alien', 'orange', 0.0),
         ('alien', 'fig', 0.0)]

现在,我要执行基本检查,以查看哪些元组的最后一个值大于0.0,然后将所得的元组转换为列表的字典:

Now I want to perform a basic check to see which tuples have the last value greater than 0.0 and then convert the resulting tuples into a dict of lists:

new_words = {'amazon': ['Amazon', 'Alexa', 'microsoft', 'Amazon Pay', 'Prime'],
             'alien': ['dell']}

我该怎么办?

推荐答案

您无法在字典中获得所需的结果,因为字典中不包含重复的键(类似于普通的英语词典:其中的单词可能拼写相同,但发音有所不同.

You can't have the desired result in a dictionary as dictionaries don't contain duplicate keys (similar to a normal English dictionary: where the words might spell the same but there are differences in pronunciation).

所需结果可以再次存储到列表中.

The desired result can be stored again into a list.

newDict = {}
result = []

Lista =[('amazon', 'Amazon', 1.0), ('amazon', 'Alexa', 0.8), ('amazon', 'microsoft', 0.6), ('amazon', 'Amazon Pay', 0.7), ('amazon', 'Prime', 0.4),('alien', 'jack' , 0.0), ('alien', 'dell', 0.6), ('alien', 'apple', 0.0), ('alien', 'orange', 0.0), ('alien', 'fig', 0.0)]

for items in Lista:
    if items[2] > 0.0:
        newDict[items[0]] = items[1]
        result.append(newDict)
        newDict = {}

print result

这篇关于如何按给定索引的项目过滤元组列表并将其转换为列表字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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