python - 如何制作具有重复值模式的字典?

标签 python dictionary

我正在尝试创建具有类似重复模式的字典

{0:"A",
1:"B",
2:"C",
3:"D",
4:"A",
5:"B",
6:"C",
7:"D",}

等等。我该怎么做?我试过使用 for 循环,但无法弄明白。

我什至不确定这是解决我的问题的正确方法。我正在使用相同的输出多次求解模拟,只为模拟的每个循环更改 1 个输入。 基本上,我最终得到了一个 DataFrame,它为每个带有列的模拟收集输出(4 个不同的系列)

[0, 1, 2, 3, 4, 5, 6, 7, 8, ...]

我想重命名

["A", "B", "C", "D", "A", "B", "C", "D",...]

或者,Python 中是否有某种数据类型,它可以提供 2 级分类,例如

[Simulation 1: ["A", "B", "C", "D"],
Simulation 2: ["A", "B", "C", "D"],
Simulation 3: ["A", "B", "C", "D"],
Simulation 4: ["A", "B", "C", "D"],
Simulation 5: ["A", "B", "C", "D"],
and so on...]

其中“A”、“B”、“C”和“D”各包含一列数据输出,每次模拟都不同?

最佳答案

您可以使用 itertools.cycle 巧妙地实现这一点:

In [1]: import itertools

In [2]: cols = [0, 1, 2, 3, 4, 5, 6, 7]

In [3]: dict(zip(cols, itertools.cycle('ABCD')))
Out[3]: {0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'A', 5: 'B', 6: 'C', 7: 'D'}

关于python - 如何制作具有重复值模式的字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65050307/

相关文章:

python - pkg_resources : get own distribution?

python - 遍历列表中的字符串

dictionary - 我如何编写 DRY golang map 操作函数

python - 是否可以在元组中使用 if ?

python - 剪切图像而不裁剪

python - urwid 中是否有焦点改变事件?

用于插入模板映射的 C++ 函数

python - 从文本文件创建深度嵌套的字典

java - 在 Java 的构造函数中初始化 Map 的更好方法

python - 如果两列中的名称使用正则表达式匹配,则创建返回 true/false 的新列