如何从字典的列表中删除特定的项?



我有一个包含键的字典,值是许多整型和浮点数的列表。例如:

{"key1": [6,4,3.2,0.04...], "key2": [17,0.9,50.79...]}

所有的列表长度相同。我想从每个列表中删除第二项(例如key1中的4和key2中的0.9)。我该怎么做呢?

试试只用一行:

d = {"key1": [6, 4, 3.2, 0.04], "key2": [17, 0.9, 50.79]}
result = {k: [j for i, j in enumerate(v) if i != 1] for k, v in d.items()}

result将为:

{'key1': [6, 3.2, 0.04], 'key2': [17, 50.79]}
dd = {"k1":[1,2,3,4],"k2":[11,22,33,44]}
from pprint import pp
pp({k:[v[0]]+v[2:]for k,v in dd.items()}) #[v[0]] - needed because in this case returns only one element and not list

结果:

{'k1': [1, 3, 4], 'k2': [11, 33, 44]}

相关内容

  • 没有找到相关文章

最新更新