python - 如果 set1 的值 = set2 的键,则将一组值替换为另一组的值?

标签 python python-3.x dictionary replace output

编辑:将字典更改为集合,因为我没有意识到 {} 表示集合。并固定为集合包含在元组中。

我想迭代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/

相关文章:

python - 在类属性更改时调用 Python 方法

python - Scrapy:从相对路径构造绝对路径的非重复列表

python-3.x - 为什么这个日期时间子类在 Python 3 上失败?

python - 是否可以在 Google Chrome 上运行 Python GUI?如果是,请告诉我如何?

python - 从矩阵到单行字典

python - 将 pandas 数据框中的值替换为另一个数据框中的值

python - 复合 if elif else 语句 + python

python - 遍历字典列表并删除那些没有 X 键的字典

python - 如何格式化最多 N 位小数的数字,其中 N 是随机的

python - 基于键的两个字典列表的交集