python - 如何将函数应用于一系列字典?
问题描述
我有以下功能:
def count_chars(e):
return len(e)
我正在迭代一个json,如下所示:
在:
a_lis = []
with open('../JSON_FILE.json','r') as fa:
a = json.load(fa)
for e in a['entries']:
pprint(e)
出去:
{'data': ['string'], 'type': 'one'}
{'data': ['a string '], 'type': 'one'}
{'data': ['another string'], 'type': 'three'}
...
{'data': ['one more string'], 'type': 'two'}
如何应用count_chars
函数并将其添加或更新为'data'
列表中的新字符串?例如,预期的输出如下所示:
{'data': ['string','6'], 'type': 'one'}
{'data': ['a string','8'], 'type': 'one'}
{'data': ['another string','14'], 'type': 'three'}
...
{'data': ['one more string','15'], 'type': 'two'}
更新:
我发现我的列表有不止一项,例如:['first', 'second string']
? 我怎样才能返回['first', len_1, 'second string', len_2]
解决方案
你可以使用append()
:
lst = [
{"data": ["string"], "type": "one"},
{"data": ["a string "], "type": "one"},
{"data": ["another string"], "type": "three"},
]
def count_chars(e):
return len(e)
for d in lst:
d["data"].append(count_chars(d["data"][0]))
print(lst)
# [{'data': ['string', 6], 'type': 'one'}, {'data': ['a string ', 9], 'type': 'one'}, {'data': ['another string', 14], 'type': 'three'}]
如果列表中有更多字符串,则可以使用extend()
并重建一个新列表:
lst = [
{"data": ["string", "hi"], "type": "one"},
{"data": ["a string "], "type": "one"},
{"data": ["another string"], "type": "three"},
]
def count_chars(e):
return len(e)
for d in lst:
newlst = []
for x in d["data"]:
newlst.extend([x, count_chars(x)])
d["data"] = newlst
print(lst)
# [{'data': ['string', 6, 'hi', 2], 'type': 'one'}, {'data': ['a string ', 9], 'type': 'one'}, {'data': ['another string', 14], 'type': 'three'}]
注意:由于count_chars()
只是简单地返回,因此调用自身len()
可能更容易。len()
推荐阅读
- python - BS4 从
标签获取信息 - django - 保持 Redis 数据在 Docker 容器中的 docker-compose down 和 up 之间保持活跃
- python-3.x - 如何为变量(或该功能)使用“b”前缀
- angular - 无法在我的 Angular 项目中安装 tailwind css
- reactjs - 清理 useEffect 挂钩中的功能问题
- reactjs - React useRef() 未显示 ref.current 的正确信息
- matlab - 我们如何通过编程在matlab的appdesigner中滚动合适?
- c++ - 逻辑与运算符和嵌套 if 语句有什么区别?
- bash - 将屏幕与 ssh 和远程 gawk 一起使用时出现语法错误
- google-tag-manager - GTM 数据层限制