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”。在
生成的字典将来自于:
^{pr2}$为此:
one ['hello'], two ['goodbye']
说明:
从右边开始
d
是字典,它存储<key, [val]>
对于
d
中的每个key, val
我们执行以下操作,[ele for ele in val if not ele.lower().endswith('ing')]
表示对列表(val
)中的每个元素(ele
)执行以下操作:if not
),那么得到ele
然后只需打印
{ key: [ele1, ele2, ..] , .. }
。您可以使用dict comprehension以一种不变的方式(即,不改变原始dict)执行此操作:
听写理解。在
已编辑以将以“ing”结尾的值替换为“removed”
^{pr2}$相关问题 更多 >
编程相关推荐