编辑:将字典更改为集合,因为我没有意识到 {} 表示集合。并固定为集合包含在元组中。
我想迭代cardTuple中的每个集合,对于每个值,将其替换为imageDict中的相应值(脸部) 。我假设我们将值与索引相匹配,并以某种方式输出脸部。也许我需要第三组或列表来在输出之前存储结果?
imageDict = dict() # Contains index:face and looks like 1 👽 2 🐕 3 🐱 4 🚑 5 🚓 6 🐼 7 🐶 8 🐸 9 🐴 10 🐰 11 🐭 12 🐬 13 🐢 14 🐝
cardTuple = ({7, 42, 15, 47, 20, 52, 25, 30}, {3, 39, 14, 47, 55, 22, 23, 31})
我目前的方法:
newList = []
newList2 = []
for i in cardTuple:
for j in i:
if i == 1: ## maybe this needs to be 0?
newList.append(imageDict[j])
elif i == 2: ## maybe 1?
newList2.append(imageDict[j])
有什么建议吗?
最佳答案
首先,正如评论中提到的,dict1
不是一个字典。它是一个集合
。但您可能想让它成为一个列表。
这是使用列表推导式获得所需内容的简单方法:
mylist = [1,5,7,10,13]
mydict = {
1:face1,2:face2,3:face3,4:face4,5:face5,6:face6,7:face7,
8:face8,9:face9,10:face10,11:face11,12:face12,13:face13
}
output = [mydict[key] for key in mylist]
>>> [face1, face5, face7, face10, face13]
关于python - 如果 set1 的值 = set2 的键,则将一组值替换为另一组的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53339438/