繁体   English   中英

在字典中,如何从具有多个值的键中删除一个值? 蟒蛇

[英]within a dictionary, how do I remove a value from a key with multiple values? Python

from collections import OrderedDict

def main():
    dictionary = OrderedDict()
    dictionary["one"] = ["hello", "blowing"]
    dictionary["two"] = ["frying", "goodbye"]

    for key in dictionary:
        print key, dictionary[key]

    user_input = raw_input("REMOVE BUILDINGS ENDING WITH ING? Y/N")
    if user_input == ("y"):
        print ""
        for key in dictionary:
            for x in dictionary[key]:
                if ("ING") in x or ("ing") in x:
                    del dictionary[key][x]

    print ""

    for key in dictionary:
        print key, dictionary[key]

main()

我正在尝试从字典中的所有键中删除其中带有“ ing”的任何项目,例如,从键“ one”中删除“ blowing”,从键“ two”中删除“ frying”。

产生的字典将来自此:

one ['hello', 'blowing'], two ['frying', 'goodbye']

对此:

one ['hello'], two ['goodbye']

字典理解。

return {x : [i for i in dictionary[x] if not i.lower().endswith('ing')] for x in dictionary}

编辑以将“ ing”结尾的值替换为“ removed”

return {x : [i if not i.lower().endswith('ing') else 'removed' for i in dictionary[x]] for x in dictionary}

您可以通过使用dict理解以不可变的方式(即,不改变原始dict)来做到这一点:

>>> d = {'one': ['hello', 'blowing'], 'two': ['frying', 'goodbye']}
>>> {k: [w for w in v if not w.lower().endswith('ing')] for k, v in d.items()}
{'one': ['hello'], 'two': ['goodbye']}

尝试这个:

>>> collections.OrderedDict({key:filter(lambda x:not x.endswith('ing'), value) for key,value in dictionary.items()})
OrderedDict([('two', ['goodbye']), ('one', ['hello'])])
{key: [ele for ele in val if not ele.lower().endswith('ing')] for key, val in d.items()}

说明:

从右边开始

  • d是字典,它存储<key, [val]>

  • 对于d每个key, val我们执行以下操作,

  • [ele for ele in val if not ele.lower().endswith('ing')]表示对于list( val )中的每个元素( ele ),我们执行以下操作:

    • 将每个字符串转换为小写
    • 检查它是否以-ing结尾
    • 然后如果这些都不是( if not ),则得到ele
  • 然后,您只需打印{ key: [ele1, ele2, ..] , .. }

您试图删除的字符串索引不是int位置参考。 这是修改后的代码:

from collections import OrderedDict

def main():
    dictionary = OrderedDict()
    dictionary["one"] = ["hello", "blowing"]
    dictionary["two"] = ["frying", "goodbye"]

    for key in dictionary:
        print key, dictionary[key]

    user_input = raw_input("REMOVE BUILDINGS ENDING WITH ING? Y/N")
    if user_input == ("y"):
        print ""
        for key,value in dictionary.iteritems():
            for i,x  in enumerate(value):
                if ("ING") in x or ("ing") in x:
                    del dictionary[key][i]

    print ""

    for key in dictionary:
        print key, dictionary[key]

main()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM