我有一本字典D如下
抱歉我没有澄清。我的新词典看起来像这样:
D = {'first':['a','b','b'], 'second':['alpha','beta','kappa']}
我想在D中搜索每个配对,如果一个键在列表中有重复的值(比如D [' first']),我想用True替换该值。
我如何使用循环和语句来解决这个问题? (这是我的任务中的问题的一部分,这些是限制)
答案 0 :(得分:0)
嗨,如果我理解正确,那可能是:
dic = {'mykey':'123345678', 'otherkey':44}
'mykey' in dic
>>>True
或您的示例生成器:
dic['mykey'] = list(map(lambda x: bool(x), dic['otherkey']))
print dic
>>>{'mykey': [True, True, True], 'otherkey': [9, 4, 7]}
或过滤器:
dic['mykey'] = list(map(lambda x: bool(x) if (x==9 or x==4 or x==3) else False, dic['otherkey']))
print dic
{'mykey': [True, True, False], 'otherkey': [9, 4, 7]}
但我不明白你需要一个循环?想要在输出中获得什么?
答案 1 :(得分:0)
我无法仅使用for
语句执行此操作,但您可以将其与while
结合使用:
for key in dict.keys():
indexCounter = 0
while indexCounter < len(dict[key]):
otherIndexCounter = 0
while otherIndexCounter < len(dict[key]):
if indexCounter != otherIndexCounter:
if dict[key][indexCounter] == dict[key][otherIndexCounter]:
dict[key][otherIndexCounter] = True
otherIndexCounter += 1
indexCounter += 1
示例:
def changeRepeated(dict):
for key in dict.keys():
indexCounter = 0
while indexCounter < len(dict[key]):
otherIndexCounter = 0
while otherIndexCounter < len(dict[key]):
if indexCounter != otherIndexCounter:
if dict[key][indexCounter] == dict[key][otherIndexCounter]:
dict[key][otherIndexCounter] = True
otherIndexCounter += 1
indexCounter += 1
return dict
dictionary = {'first':['a','b','b'], 'second':['alpha','beta','kappa']}
dictionary = changeRepeated(dictionary)
print(dictionary)
>>> {'first': ['a', 'b', True], 'second': ['alpha', 'beta', 'kappa']}
这就是你的输出:
{'first': ['a', 'b', True], 'second': ['alpha', 'beta', 'kappa']}
我希望它有所帮助:)。