我太笨了,就是各种 for
tmp = {
"a": [
{"a1": "tom"},
{"a2": "jery"},
{"a3": "jery"},
{"a4": "cao"},
{"a5": "cao"},
],
"b": [
{"b1": "lily"},
{"b2": "lily"},
{"bn": "jack"},
]
}
ret = {
"a": [
{"a1": "tom"},
{"a2": "jery"},
{"a4": "cao"}
],
"b": [
{"b1": "lily"},
{"bn": "jack"}
]
}
_sort = {}
t = []
for k, v in tmp.items():
_sort[k] = []
for i in v:
if list(i.values())[0] not in t:
t.append(list(i.values())[0])
_sort[k].append(i)
print(_sort)
1
cyspy 2020-08-26 20:17:29 +08:00 via Android
反着放到 dict 里再取出来
|
2
lybcyd 2020-08-26 20:43:11 +08:00
如果不同的 key 有相同的 value,该保留哪一个呢?
|
4
css3 OP 测试了一下,我这一坨还有 bug😂
|
5
css3 OP @css3 就是不同 keykey 的 value 可以允许重复
tmp = { "a": [ {"a1": "tom"}, {"a2": "jery"}, {"a3": "jery"}, {"a4": "cao"}, {"a5": "cao"}, ], "b": [ {"b1": "lily"}, {"b2": "lily"}, {"bn": "jack"}, {"bb": "tom"} ] } ret = { "a": [ {"a1": "tom"}, {"a2": "jery"}, {"a4": "cao"} ], "b": [ {"b1": "lily"}, {"bn": "jack"}, {"bb": "tom"} ] } |
6
ruyu 2020-08-26 21:08:43 +08:00
```py
[(k, [(n, m) for m, n in dict([reversed(next(iter(i.items()))) for i in v]).items()]) for k, v in tmp.items()] ``` 这样? |
7
ruyu 2020-08-26 21:11:09 +08:00
忘了转成 dict 了. 那就这样?
dict([(k, dict([(n, m) for m, n in dict([reversed(next(iter(i.items()))) for i in v]).items()])) for k, v in tmp.items()]) |
8
Death 2020-08-26 21:22:04 +08:00
平时 python 写的不多,试着写了一下
``` ret={key:list(reversed([{v:k} for k,v in {y:x for d in reversed(val) for x,y in d.items()}.items()])) for key,val in tmp.items()} ``` |
9
djFFFFF 2020-08-26 21:22:14 +08:00
这个结构太奇怪了,字典套列表再套只会有一个元素的字典是什么操作,字典套字典不行吗?
|
10
ipwx 2020-08-26 21:40:02 +08:00
其实楼主你有没有发现,一行写法更难读。。。
所以一步一步做是坠好的。 |
11
Trim21 2020-08-26 21:41:18 +08:00
封装成个函数用的时候也是一行(强行
|
12
BiteTheDust 2020-08-26 21:53:10 +08:00
应该反过来存储 合理存放数据结构很重要
|
13
billgreen1 2020-08-27 16:21:05 +08:00
[
{"a1": "tom"}, {"a2": "jery"}, {"a3": "jery"}, {"a4": "cao"}, {"a5": "cao"}, {"a6": "jery"}, ], 这种情况如何处理?@楼主 |
14
css3 OP |
15
css3 OP |
16
skinny 2020-08-27 20:09:47 +08:00
不要在复杂数据结构和逻辑下写所谓的一行代码,看上去高大上,实际难读难以理解没卵用,先不提以后再读和维护时的酸爽,写的时候你也多浪费了很多脑细胞和时间。
|
17
ipwx 2020-08-28 09:45:53 +08:00
|
20
wwf 2020-08-28 15:17:53 +08:00
def unpack(lst):
value_set = set() new_lst = [] for i in lst: for k, v in i.items(): if not value_set: value_set.add(v) new_lst.append(i) if v in value_set: continue value_set.add(v) new_lst.append(i) return new_lst ret = {} for k, v in tmp.items(): ret[k] = unpack(v) |