我想将dictionary_values中的空列表替换为随机字符,例如“ a”。
我的输入:
k = [{'1': 'man'},
{'8': []},
{'3': 'chester'},
{'5': 'united'},
{'7': 'one'},
{'0': 'man'},
{'2': 'army'},
{'4': 'my'},
{'6': 'random'},
{'9': 'example'},
{'1': 'for'},
{'8': []},
{'3': 'asking'},
{'5': 'in'},
{'7': 'stack'},
{'0': 'over'},
{'2': 'flow'},
{'4': 'expert'},
{'6': 'people'},
{'9': 'yes'}]
我当前的代码:
for i in k:
for u, l in i.items():
if "[]" in l:
l.replace("[]", "a")
print(l)
我尝试运行此代码,但没有输出。我想尽可能将所有的[[]]替换为“ a”。可以实现吗?
答案 0 :(得分:2)
您试图用字符串替换[]
类型的字符串,而您应该更新字典的值。另外,您在第if "[]" in l:
行中进行了错误的条件检查,其中l是一个空列表,它与字符串"[]"
相比将永远不会返回True
for i in k:
for u, l in i.items():
if []==l:
i[u]='a'
print(l)
[{'1':'man'},
{'8':'a'},
{'3':'chester'},
{'5':'团结'},
{'7':'一个'},
{'0':'man'},
{'2':'army'},
{'4':'我的'},
{'6':'random'},
{'9':“示例”},
{'1':'for'},
{'8':'a'},
{'3':'问'},
{'5':'in'},
{'7':'stack'},
{'0':'结束'},
{'2':'流'},
{'4':'专家'},
{'6':'人民'},
{'9':'是'}]
答案 1 :(得分:1)
for i in k:
for u, l in i.items():
if type(l) == list and not l:# Check If type is list and if its empty
l = 'a'#just assign a instead of using replace which is used in string
print(l)
您可以检查列表中对象的类型,而不是字符串'[]'
答案 2 :(得分:1)
您的代码中有2个错误。
if
条件是错误的。不必检查"[]"
(这是string
),而必须检查[]
(这是一个列表)。 使用以下循环,它应该可以工作。
for i in k:
for u, l in i.items():
if l == []:
i[u]="a"
答案 3 :(得分:1)
您可以尝试一下。 -
k = [i if i.values() != [[]] else {i.keys()[0]:"a"} for i in k ]
print(k)
结果-
[{'1': 'man'},
{'8': 'a'},
{'3': 'chester'},
{'5': 'united'},
{'7': 'one'},
{'0': 'man'},
{'2': 'army'},
{'4': 'my'},
{'6': 'random'},
{'9': 'example'},
{'1': 'for'},
{'8': 'a'},
{'3': 'asking'},
{'5': 'in'},
{'7': 'stack'},
{'0': 'over'},
{'2': 'flow'},
{'4': 'expert'},
{'6': 'people'},
{'9': 'yes'}]