pythondict.fromkeys公司函数为参数

2024-10-01 02:34:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要将来自test_input的数据与classes分组,也就是说,如果来自test_input的两个值相同,它们应该具有相同的类。在

我试图创建一个字典,但不知道如何进行类管理:

@pytest.mark.parametrize("test_input,expected", [
    ([23,33,33,53,63,73,83,93,103], 'dictwithclass'),
])
def test_colorize(test_input, expected):    
    classes = ("colore1","colore2","colore3","colore4","colore5","colore6","colore7","colore8","colore9","colore10")

    insiemi=set(test_input)

    result = dict.fromkeys(insiemi, classi)

应输出:

{33: "colore1", 83: "colore2", 53: "colore3", 103: "colore4", 73: "colore5", 23: "colore6", 93: "colore7", 63: "colore8"}


Tags: 数据testinput字典classesexpectedcolore6colore1
1条回答
网友
1楼 · 发布于 2024-10-01 02:34:26

dict.fromkeys()将把所有键设置为相同的单个值。不能使用它来设置多个不同的值。在

使用zip()将键和值配对,然后将生成的(key, value)对序列直接传递给dict()类型:

classes = ('colore1', 'colore2', 'colore3', 'colore4', 'colore5', 'colore6', 'colore7', 'colore8', 'colore9', 'colore10')
result = dict(zip(set(test_input), classes))

请注意,因为set()对象是无序的对象,所以您不一定知道这里哪个类有什么键。对于整数值,这个顺序在解释器的调用之间是稳定的,但是不同的Python版本和Python版本的顺序可能不同。在

演示:

^{pr2}$

以上假设的唯一键永远不会超过10个;最好在此处生成类名:

result = {key: 'colore{}'.format(i) for i, key in enumerate(set(test_input), 1)}

它使用enumerate()函数为集合中的每个元素编号(从1开始),然后使用该数字生成类名。在

相关问题 更多 >