gpt4 book ai didi

python : Remove the key if its value is lower than 2

转载 作者:行者123 更新时间:2023-12-02 02:21:03 25 4
gpt4 key购买 nike

有一个包含2个字典的列表,如果我想删除包含小于2的值的'zxc'的键,下一步该怎么做?

aa = [{'asd': 'qwe', 'zxc': 5}, {'zxc': 1, 'rty': 'uio'}]

def try_test():
if 'zxc' < 2:
del aa['zxc']

但它不起作用。

最佳答案

代码中的问题是 aa 是字典列表,因此 aa['zxc'] 不清楚。

相反,您应该循环遍历列表中的每个索引并进行如下比较:

aa = [{'asd': 'qwe', 'zxc': 5}, {'zxc': 1, 'rty': 'uio'}]

def try_test():
for ind in aa:
if ind['zxc'] < 2:
del ind['zxc']

print(aa)

try_test()

输出:

[{'zxc': 5, 'asd': 'qwe'}, {'rty': 'uio'}]

关于 python : Remove the key if its value is lower than 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59015124/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com