我想做一个上下文无关的语法简化软件。 当涉及到从字典的值甚至键值对中删除某些特定的项时,我会感到困惑。你知道吗
问题是它没有遵循一种模式。你知道吗
如果元素属于V1,我需要将它保存在字典中。 (V1是派生终端的所有值的列表,我只需要在字典中保留这些值,但没那么简单)
如果元素不属于V1并且dictionary的值是字符串,则需要删除该元素。
如果元素不属于V1并且dictionary的值是一个列表,我需要检查它是否是该列表中的单个元素,如果是,请删除Value。
失败的循环在下面。 我把修改词典时弄不懂逻辑的部分打印出来了。你知道吗
counter = 0
for k,v in derivations.items():
derivationsCount = len(v)
while counter < derivationsCount:
if lista_ou_string(v[counter]): # returns True for lists, False for else
sizeOfList = len(v[counter])
counter2 = 0
while counter2 <= (sizeOfList - 1):
if v[counter][counter2] not in V1:
if derivationsCount == 1:
print("# NEED TO DELETE BOTH KEY AND VALUE FROM derivatios.items()")
else:
print("# NEED TO DELETE ONLY THE VALUE FROM derivations.items()")
counter2 += 1
else: # strings \/
if v[counter] not in V1:
if derivationsCount == 1:
print("# NEED TO DELETE BOTH KEY AND VALUE FROM derivatios.items()")
else:
print("# NEED TO DELETE ONLY THE VALUE FROM derivations.items()")
else:
print("# DO NOT DELETE ANYTHING! ALL LISTS ELEMENTS BELONGS TO 'V1'")
counter += 1
人们不想在循环浏览字典(或列表)时对其进行修改。因此,我创建了
derivations
-new_derivations
的副本并修改了这个new_derivations
:实际上,我将以不同的方式实现上述代码:不要考虑从
derivations
中删除项,而要考虑何时应该将元素添加到列表中。这样代码就简单多了:如果要从字典中删除键、值对,请使用
del
:如果要删除值,但保留键,可以尝试分配键
None
:相关问题 更多 >
编程相关推荐