python - 检查列表中是否有重复的对并替换其中一个值
问题描述
我有字典的值作为列表:
myDict = {'id1': ["name1","Type1","Value_1"],
'id2': ["name2","Type1","Value_2"],
'id3': ["name1","Type2","Value_3"],
'id4': ["name1","Type1","Value_4"]
}
我想遍历字典并查看名称和类型对是否已经在列表中 - 用任何其他替换“类型 1”值,结果字典将是:
myDict = {'id1': ["name1","Type1","Value_1"],
'id2': ["name2","Type1","Value_2"],
'id3': ["name1","Type2","Value_3"],
'id4': ["name1","Modified_Type 1","Value_4"]
}
目前不知道如何用 Python 处理它
主要是关于比较 value[0]、value[1] 以及两者在其他列表中是否相同的问题 - 替换它。
我正在尝试遍历现有字典并比较它的值是否不在 newDictionary 中,但显然我正在检查这些值是否单独存在于 newDict 值中,而不是作为对:
myDict = {'id1': ["name1","Type1","Value_1"],
'id2': ["name2","Type1","Value_2"],
'id3': ["name1","Type2","Value_3"],
'id4': ["name1","Type1","Value_4"]
}
newDict = {}
for key, value in myDict.items():
if value[0] not in newDict.values() and value[1] not in newDict.values():
newDict[key] = value
else:
newDict[key] = [value[0],"Some modified value",value[2]]
print (newDict)
解决方案
目前还不清楚您到底想要什么,因为您的结果包含 Type1 两次......但这是一种开始正确道路的方法。
听起来您希望对您的 id 进行排序。所以你可以得到一个排序的键列表,如下所示:
keys = sorted(myDict) #thanks @abarnert
然后遍历并检查类型:
existingTypes = []
for key in keys:
theType = myDict[key][1]
if theType in existingTypes:
myDict[key][1] = "Modified_" + theType
else:
existingTypes.push(theType)
编辑 - 更新您更新的问题:
这可能不是最干净的,但它会起作用:
myDict = {'id1': ["name1","Type1","Value_1"],
'id2': ["name2","Type1","Value_2"],
'id3': ["name1","Type2","Value_3"],
'id4': ["name1","Type1","Value_4"]
}
newDict = {}
for key in sorted(myDict):
value = myDict[key]
valuesExist = False
for newValue in newDict.values():
if value[0] == newValue[0] and value[1] == newValue[1]:
valuesExist = True
if not valuesExist:
newDict[key] = value
else:
newDict[key] = [value[0],"Some modified value",value[2]]
print (newDict)
推荐阅读
- c# - 在 C# 中将带有子字段的父属性显示到 datagridview
- r - ChoiceModelR 会改变案例的顺序吗?
- ruby-on-rails - Ruby on rails 5.2 - 具有活动存储的背景图像
- java - 如果这个或那个带有字符串
- android - RecylerView Toasts only first item 无论点击的项目
- wordpress - AMP 网站/URL 显示空白页
- sql-server - SQL 查询 - “TypeError: sequence item 0: expected string, Decimal found” 使用值
- python-3.x - 将熊猫系列转换为数据框
- .net - ReCaptcha 2.0 远程服务器返回错误(错误请求)
- python - 尝试创建表时出现“ValueError:格式中的零长度字段名称”