我有一個形式的字典:
{"level":[1,2,3], "conf":[-1,1,2], "text":["here","hel","llo"]}
我想過濾串列以洗掉 index 處的每個專案i,其中"conf"indexi不是>0。
例如,如果我有這樣的輸入:
{"level":[1,2,3], "conf":[-1,1,2], "text":["here","hel","llo"]}
輸出應該是這樣的:
{"level":[2,3], "conf":[1,2],text:["hel","llo"]}
因為 的第一個值conf不 > 0。
我嘗試過這樣的事情:
new_dict = {i: [a for a in j if a >= min_conf] for i, j in my_dict.items()}
但這僅適用于一把鑰匙。
回復:下面有很多好的解決方案。我只是想到了另一個。
- 將此串列結構的字典轉換為元組串列:
tuples =[(1,-1,"here"), (2, 1, "hel"),(3,"2","llo")] - 然后我只需要按每個元組的第二項過濾這個串列,這很容易:
filter(lambda item: item[1] >= 0, tuples)
uj5u.com熱心網友回復:
嘗試:
from operator import itemgetter
def filter_dictionary(d):
conf = d['conf']
positive_indices = [i for i, item in enumerate(conf) if item > 0]
f = itemgetter(*positive_indices)
return {k: list(f(v)) for k, v in d.items()}
d = {"level": [1, 2, 3], "conf": [-1, 1, 2], "text": ["-1", "hel", "llo"]}
print(filter_dictionary(d))
輸出:
{'level': [2, 3], 'conf': [1, 2], 'text': ['hel', 'llo']}
我首先嘗試查看 的哪些索引'conf'是正數,然后itemgetter從字典中的值中選擇這些索引。
uj5u.com熱心網友回復:
我將保留有效元素(大于 0)的索引:
kept_keys = [i for i in range(len(my_dict['conf'])) if my_dict['conf'][i] > 0]
然后您可以過濾每個串列,檢查串列中某個元素的索引是否包含在kept_keys:
{k: list(map(lambda x: x[1], filter(lambda x: x[0] in kept_keys, enumerate(my_dict[k])))) for k in my_dict}
輸出:
{'level': [2, 3], 'conf': [1, 2], 'text': ['hel', 'llo']}
uj5u.com熱心網友回復:
我用這個解決了它:
from typing import Dict, List, Any, Set
d = {"level":[1,2,3], "conf":[-1,1,2], "text":["-1","hel","llo"]}
filtered_indexes = set([i for i in range(len(d.get('conf', []))) if d.get('conf')[i] > 0])
def filter_dictionary(d: Dict[str, List[Any]], filtered_indexes: Set[int]) -> Dict[str, List[Any]]:
for key, list_values in d.items():
d[key] = [value for i, value in enumerate(list_values) if i in filtered_indexes]
return d
print(filter_dictionary(d, filtered_indexes))
輸出:
{'level': [2, 3], 'conf': [1, 2], 'text': ['hel', 'llo']}
uj5u.com熱心網友回復:
a = {"level":[1,2,3], "conf":[-1,1,2],"text":["-1","hel","llo"]}
for k, v in a.items():
if k == "conf":
for element in v:
if element < 0:
to_delete = [] #it will store the index numbers of the conf that you want to delete(conf<0)
to_delete.append(v.index(element))
for position in to_delete:
for k, v in a.items():
v.pop(position)
然后 a 將是 {'level': [2, 3], 'conf': [1, 2], 'text': ['hel', 'llo']} 這就是你想要的。
uj5u.com熱心網友回復:
您可以使用一個函式來計算要保留哪些索引并僅使用這些索引重新構造每個串列:
my_dict = {"level":[1,2,3], "conf":[-1,1,2],'text':["-1","hel","llo"]}
def remove_corresponding_items(d, key):
keep_indexes = [idx for idx, value in enumerate(d[key]) if value>0]
for key, lst in d.items():
d[key] = [lst[idx] for idx in keep_indexes]
remove_corresponding_items(my_dict, 'conf')
print(my_dict)
按要求輸出
uj5u.com熱心網友回復:
很多很好的答案。這是另一種 2-pass 方法:
mydict = {"level": [1, 2, 3], "conf": [-1, 1, 2], 'text': ["-1", "hel", "llo"]}
for i, v in enumerate(mydict['conf']):
if v <= 0:
for key in mydict.keys():
mydict[key][i] = None
for key in mydict.keys():
mydict[key] = [v for v in mydict[key] if v]
print(mydict)
輸出:
{'level': [2, 3], 'conf': [1, 2], 'text': ['hel', 'llo']}
uj5u.com熱心網友回復:
我相信這會奏效:
d = {"level":[1,2,3], "conf":[-1,1,2], "text":["-1","hel","llo"]}
for key in d:
if key != "conf":
d[key] = [d[key][i] for i in range(len(d[key])) if d["conf"][i] >= 0]
d["conf"] = [i for i in d["conf"] if i>=0]
print(d)
輸出:
{'level': [2, 3], 'conf': [1, 2], 'text': ['hel', 'llo']}
uj5u.com熱心網友回復:
嘗試這個:
a_dict = {"level": [1, 2, 3], "conf": [-1, 1, 2], "text": ["-1", "hel", "llo"]}
for a_list in a_dict.values():
print(a_list)
iterations = 0
for item in a_list[::-1]:
if iterations >= 2:
a_list.remove(item)
iterations = 1
print(a_dict)
輸出:
{'level': [2, 3], 'conf': [1, 2], 'text': ['hel', 'llo']}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/429000.html
上一篇:合并兩個字典
