猿问

将python字典转换为python列表

dictionary = {0:0.2, 9:0.4}


pylist = [0.2, 0, 0, 0, 0, 0, 0, 0, 0, 0.4]

将字典转换为pylist的有效方法是哪一种?字典中的键构成列表中的索引,并且字典中的各个值成为列表中的值。字典中的键范围介于0到9之间(含0和9)。列表的长度将是固定的,即10。


pytuple = [ (0, 0.2), (9,0.4)]


pylist = [0.2, 0, 0, 0, 0, 0, 0, 0, 0, 0.4]

或者,哪种是将pytuple转换为pylist的有效方法?元组中的第一个元素形成列表中的索引,元组中的相应第二个值成为列表中的值。字典中的键范围介于0到9之间(含0和9)。列表的长度将是固定的,即10。


MM们
浏览 135回答 1
1回答

眼眸繁星

我做了一些将字典转换为pylist的测量,结果如下:from timeit import timeit    dictionary = {0:0.2, 9:0.4}def method1(d, n=10):    return [d[i] if i in d.keys() else 0 for i in range(n)]def method2(d, n=10):    return [d.get(i, 0) for i in range(n)]def method3(d, n=10):    return [d.get(i, v) for i, v in enumerate([0] * n)]def method4(d, n=10):    l = [0] * n    for v, k in dictionary.items():        l[v] = k    return lprint(timeit("method1(dictionary)", globals=globals(), number=1_000_000))print(timeit("method2(dictionary)", globals=globals(), number=1_000_000))print(timeit("method3(dictionary)", globals=globals(), number=1_000_000))print(timeit("method4(dictionary)", globals=globals(), number=1_000_000))输出为:1.87132723000013361.88947214499967232.150105588000770.5128111490002993很明显,这method4是最快的-首先创建固定的零列表,然后仅迭代需要更改的键。基于这一事实,将元组转换为列表应遵循类似的模式:创建固定列表,然后遍历pytuple并更改该列表中的值。编辑:我也对随机词典做了一些测试:# creating random dictionaryn = random.randint(1000, 100000)idx = list(range(n))dictionary = {}for i in range(random.randint(100, n)):    dictionary[random.choice(idx)] = random.random()print('n =',n)print('len(dictionary.keys() =', len(dictionary.keys()))print(timeit(f"method1(dictionary, n={n})", globals=globals(), number=100))print(timeit(f"method2(dictionary, n={n})", globals=globals(), number=100))print(timeit(f"method3(dictionary, n={n})", globals=globals(), number=100))print(timeit(f"method4(dictionary, n={n})", globals=globals(), number=100))结果:n = 82981len(dictionary.keys() = 320831.2032332969993151.11942717399870161.36682709199885720.2243523440010904
随时随地看视频慕课网APP

相关分类

Python
我要回答