【问题标题】:Remove Object in Json File Python删除 Json 文件 Python 中的对象
【发布时间】:2020-12-15 18:31:34
【问题描述】:

我有一个 json 文件:

[{"uid": x, "username": "x", "firstname": "x", "lastname": "x", "access_hash": x}, {"uid": y, "username": "y", "firstname": "y", "lastname": "y", "access_hash": y}]

我想在循环中删除对象 {"uid[...]"access-hash": x}

我有以下代码:

 try:
                user_to_add = InputPeerUser(user['uid'], user['access_hash'])
                add = await client(InviteToChannelRequest(target_group_entity,[user_to_add]))
                print(gr+'Added ', str(user['uid']))
                #remove the object where I used uuid acces_hash and so on

我希望有人可以帮助我,并提前联系!

【问题讨论】:

标签: python json telethon


【解决方案1】:

请在以后尝试阅读Stack Overflow guidelines for questions posting,以便清楚完整地描述您的问题。一般来说,提供上下文会有很大帮助。

关于你的问题,我会做一些假设。第一个是您正在遍历用户对象数组,第二个是每个对象都是唯一的。

您应该使用pop() List 方法,因为您要删除刚刚添加到频道的用户对象。

一个简单的例子是:

while(len(users_list)>0):
     users.pop(0) # You are removing the current object of the users_list.

由于您要从列表中删除对象,因此它的长度将在逻辑上开始减少,直到它打破 while 条件。

【讨论】:

    【解决方案2】:

    您可以使用pop()

    my_dict = [{"uid": 'x', "username": "x", "firstname": "x", "lastname": "x", "access_hash": 'x'}, {"uid": 'y', "username": "y", "firstname": "y", "lastname": "y", "access_hash": 'y'}]
    
    for i in range(0,len(my_dict)-1):
        if my_dict[i]['uid'] == 'x':
            my_dict.pop(i)
    print(my_dict)
    

    【讨论】:

    • 谢谢,但我想删除整个内容,例如:{"uid": 'x', "username": "x", "firstname": "x", "lastname": "x", "access_hash": 'x'}
    猜你喜欢
    • 1970-01-01
    • 2017-03-25
    • 2021-09-01
    • 1970-01-01
    • 2020-12-05
    • 1970-01-01
    • 1970-01-01
    • 2020-12-27
    • 1970-01-01
    相关资源
    最近更新 更多