【问题标题】:List of Dictionary Manipulation in pythonpython中的字典操作列表
【发布时间】:2018-08-10 20:42:39
【问题描述】:

我有以下表格的列表:

oldlist = [{'x': 1, 'y':2},{'x':2, 'y':2},{'x':1, 'y':3},{'x':1, 'y':2},{'x':3, 'y':4}]  

转换成

final = [{'x':1,'y':[2,3,2],'count':3},{'x':2,'y':[2],'count':1},{'x':3,'y':[4],'count':1}]  

我试过了

oldlist = [{'x': {'a':1,'b':2}, 'y':2},{'x':{'a':6,'b':7}, 'y':2},{'x':{'a':1,'b':2}, 'y':3},{'x':{'a':1,'b':2}, 'y':2},{'x':{'a':10,'b':11}, 'y':4}]  
list1=[]  
list2=[]  
list3=[]  
s = set([d['x'] for d in oldlist])  
news=list(s)  
for item in oldlist:  
if item['x'] == news[0]:  
      list1.append(item['y'])  

if item['x'] == news[1]:  
      list2.append(item['y'])  

if item['x'] == news[2]:  
      list3.append(item['y'])  
final=[]  
dic1 = {'x':news[0],'y':list1,'count':len(list1)}  
dic2 = {'x':news[1],'y':list2,'count':len(list2)}  
dic3 = {'x':news[2],'y':list3,'count':len(list3)}  
final.append(dic1)  
final.append(dic2)  
final.append(dic3)  
print final

有没有更简单的方法呢?另外在这里我知道 x 只能有三个值,所以我创建了三个变量 list1、list2 和 list3。如果 x 可以有其他几个值,我必须找到一个类似的字典列表,比如 final!它也应该适用于字符串!

【问题讨论】:

  • 你可以用s_list = sorted(s)set创建一个list。 (如果您不关心它的排序,或者只是 s_list = list(s)。)
  • @leekaiinthesky 这将适用于本示例,但不适用于可以具有各种其他 x 值的其他示例。

标签: python


【解决方案1】:

您可以将字典收集到defaultdict,其中键是来自原始字典的x,值是相关y 值的列表。然后使用列表推导生成最终结果:

from collections import defaultdict

l = [{'x':1, 'y':2},{'x':2, 'y':2},{'x':1, 'y':3},{'x':1, 'y':2},{'x':3, 'y':4}]
res = defaultdict(list)
for d in l:
    res[d['x']].append(d['y'])
final = [{'x': k, 'y': v, 'count': len(v)} for k, v in res.items()] # [{'y': [2, 3, 2], 'x': 1, 'count': 3}, {'y': [2], 'x': 2, 'count': 1}, {'y': [4], 'x': 3, 'count': 1}]

【讨论】:

  • 这是我在运行您的代码时遇到的错误。 TypeError:不可散列的类型:'dict'
  • @glitterati 您是这样运行解决方案还是修改它?您可以尝试将示例复制并粘贴到单独的文件中并尝试运行它吗?
  • 我稍微修改了一下。实际上,我的示例中的旧列表中的 x 字段是字典。因此错误。您能否建议在 x 是 dict 项目且 y 相同的情况下该怎么做。如果您愿意,我可以相应地修改问题!
  • 将元组的 dict 转换为 frozenset 并将其用作键:frozenset(x.items())
【解决方案2】:
x_list = [item['x'] for item in list1]
set_value = set(x_list)
final_lst = []

for i in set_value:
   d = {}
   d['x'] = i
   d['count'] = x_list.count(i)
   d['y'] = []
   for item in list1:
       if item['x'] == d['x']:
          d['y'].append(item['y'])
   final_lst.append(d)  
print ("Final List", final_lst)

【讨论】:

    【解决方案3】:

    好的,我在这里使用了一个小技巧来完成这项工作,这不是最 Pythonic 的方式,但它仍然可以得到你想要的答案。 问题是索引?因此 a 将 s 更改为 t,其中 t 是一个列表并更改了代码的结尾,因为您必须将字典上的键作为字符串,所以 x 变为 'x' 等等。

    查看下面的完整代码:

    lista = [{'x':1, 'y':2},{'x':2, 'y':2},{'x':1, 'y':3},{'x':1, 'y':2},{'x':3, 'y':4}]  
    
    
    list1=[]
    list2=[]
    list3=[]
    for d in lista:
        print(d)
    s = set([d['x'] for d in lista])
    t = []
    for element in s: #turn t into a list which has the same ordering as s
        t.append(element)
    for item in lista:
        if item['x'] == t[0]:
              list1.append(item['y'])
    
        if item['x'] == t[1]:
              list2.append(item['y'])
    
        if item['x'] == t[2]:
              list3.append(item['y'])
    final=[]
    dic1 = {'x':t[0],'y':list1,'count':len(list1)}
    dic2 = {'x':t[1],'y':list2,'count':len(list2)}
    dic3 = {'x':t[2],'y':list3,'count':len(list3)}
    final.append(dic1)
    final.append(dic2)
    final.append(dic3)   
    print(final)
    

    【讨论】:

    • 这适用于本示例,但不适用于 x 的不同值可能大于 3 的其他示例。这是我首先提出的问题。
    • 哦,稍微改一下逻辑:(对不起,我点击“Enter”错了,我还在想怎么解决这个问题)。
    猜你喜欢
    • 2018-05-10
    • 2018-06-30
    • 1970-01-01
    • 2019-01-29
    • 2016-10-01
    • 1970-01-01
    • 2015-12-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多