简体   繁体   English

从字典列表中的字典值中查找唯一字符串对的优雅方式

[英]Elegant way of finding unique string pairs from dictionary values in a list of dictionaries

I have a list of dictionaries: 我有一个词典列表:

    some_list = [
                  {
                     item1:'a', 
                     item2:['1', '2']
                  }, 
                  {
                     item1:'b', 
                     item2:['1', '2']
                  }, 
                  {
                     item1:'a', 
                     item2:['1']
                  }
                ]

I would like to get: 我想得到:

['a 1', 'a 2', 'b 1', 'b 2'] where each value from item 1 is paired with value from item 2 for each dictionary, and then only the unique strings are left. ['a 1','a 2','b 1','b 2']其中第1项中的每个值与每个字典中第2项的值配对,然后只留下唯一的字符串。

I can think of an obvious way to do it, namely: 我可以想到一个明显的方法,即:

  1. iterate through the some_list; 遍历some_list;
  2. for each dictionary, get a each['item_1'] and each['item_2'] 对于每个字典,获取每个['item_1']和每个['item_2']
  3. for member of each['item_2'] do each['item_1'] + ' ' + member 对于每个['item_2']的成员,每个['item_1'] +''+成员
  4. Now, make the list into a set and I have my unique values 现在,将列表设置为一个集合,我有我唯一的值

I am wondering if these is a more elegant way to do it using list comprehension. 我想知道这些使用列表理解是否更优雅。

If order doesn't matter, then you can easily translate your logic into a set-comprehnsion (and convert to list if you'd like): 如果顺序无关紧要,那么您可以轻松地将逻辑转换为set-comprehnsion(如果您愿意,可以转换为list ):

In [1]: some_list = [
   ...:                   {
   ...:                      'item1':'a',
   ...:                      'item2':['1', '2']
   ...:                   },
   ...:                   {
   ...:                      'item1':'b',
   ...:                      'item2':['1', '2']
   ...:                   },
   ...:                   {
   ...:                      'item1':'a',
   ...:                      'item2':['1']
   ...:                   }
   ...:                 ]

In [2]: {f"{d['item1']} {v}" for d in some_list for v in d['item2']}
Out[2]: {'a 1', 'a 2', 'b 1', 'b 2'}
def fun(item):
     return [item[item1]+' '+k for k in item[item2]]
res = []
[res.append(fun(i)) for i in some_list if(fun(i)) not in res]
print res

this should work 这应该工作

another formatting option, runs back to 2.7 另一个格式化选项,运行回2.7

sorted(map(' '.join,
           {(d['item1'], v)
            for d in some_list
                for v in d['item2']}))

still a 'one-liner' but with decorative line breaks and indentation 仍然是一个“单线”,但有装饰线断裂和缩进

inner list comp same as other ans, arrived at independently without seeing it 1st 内部列表与其他ans相同,在没有看到第一个的情况下独立到达

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM