[英]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: 我可以想到一个明显的方法,即:
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.