有没有更好的方法来搁置删除键的特定值?

时间:2019-05-10 13:29:02

标签: python python-3.x

编写代码以存储和编辑shelve中存储的对象

def del_key_op():

    keyword = sysargv[1]
    try:
        db = shelve.open(datafile, flag='c', writeback=True)
    except FileNotFoundError:
        return

    KEY_WORDS = db['key']
    MESSAGES = db['msg']
    NEW_KEYWORDS = []
    NEW_MSGS = []
    i=0
    for dbkey in KEY_WORDS:
        split_keys = dbkey.split()
        if keyword in split_keys:

            k=0
            for newdbkey in KEY_WORDS:
                if i==k:
                    k-=1
                    continue
                NEW_KEYWORDS.append(KEY_WORDS[k])
                NEW_MSGS.append(MESSAGES[k])
                k+=1

            db['key'] = NEW_KEYWORDS
            db['msg'] = NEW_MSGS
            db.close()
            return 
        i+=1
    db.close()
    return 

1 个答案:

答案 0 :(得分:0)

KEY_WORDS = db['key']
MESSAGES = db['msg']
NEW_KEYWORDS = []
NEW_MSGS = []
i=0
for dbkey in KEY_WORDS:
    split_keys = dbkey.split(',')
    if keyword in split_keys:
        i+=1

        continue
    NEW_KEYWORDS.append(KEY_WORDS[i])
    NEW_MSGS.append(MESSAGES[i])
    i+=1
db['key'] = NEW_KEYWORDS
db['msg'] = NEW_MSGS

db.close()