如果列表值还不是字典键,则从列表中添加字典键

时间:2020-07-06 13:22:42

标签: python dictionary-comprehension

有没有一种方法可以使以下代码更有效?即,如何避免需要先制作空字典?


lst = [1,1,2,2,3,4,4,4]

dct = {}

dct = {num: lst.count(num) for num in lst if num not in dct}

谢谢。

2 个答案:

答案 0 :(得分:1)

您可以使用fig,axs = plt.subplots(3,2,figsize = (22,15)) axs[0, 0].plot(df_7.loc['2020-06-05 00:00:00':'2020-06-05 23:45:00',['RadH1','RadM1','Up','Down']],label = ('RadH1','RadM1','Up','Down')) axs[0, 0].set_title('Summer-High Radiation',fontsize = 16) axs[0, 0].legend() axs[0, 1].plot(df_7.loc['2020-05-17 00:00:00':'2020-05-17 23:45:00',['RadH1','RadM1','Up','Down']],label = ('RadH1','RadM1','Up','Down')) axs[0, 1].set_title('Summer-Cloudy',fontsize = 16) axs[0, 1].legend() axs[1, 0].plot(df_7.loc['2020-03-15 00:00:00':'2020-03-15 23:45:00',['RadH1','RadM1','Up','Down']],label = ('RadH1','RadM1','Up','Down')) axs[1, 0].set_title('Winter-High Radiation No Snow',fontsize = 16) axs[1, 0].legend() axs[1, 1].plot(df_7.loc['2020-03-08 00:00:00':'2020-03-08 23:45:00',['RadH1','RadM1','Up','Down']],label = ('RadH1','RadM1','Up','Down')) axs[1, 1].set_title('Winter-High Radiation with Snow',fontsize = 16) axs[1, 1].legend() axs[2, 0].plot(df_7.loc['2020-03-17 00:00:00':'2020-03-17 23:45:00',['RadH1','RadM1','Up','Down']],label = ('RadH1','RadM1','Up','Down')) axs[2, 0].set_title('Winter- Cloudy No Snow',fontsize = 16) axs[2, 0].legend() axs[2, 1].plot(df_7.loc['2020-03-10 00:00:00':'2020-03-10 23:45:00',['RadH1','RadM1','Up','Down']],label = ('RadH1','RadM1','Up','Down')) axs[2, 1].set_title('Winter- Cloudy Snow',fontsize = 16) axs[2, 1].legend() plt.tight_layout()

set()

哪个产量

lst = [1,1,2,2,3,4,4,4]

dct = {key: lst.count(key) for key in set(lst)}
print(dct)

答案 1 :(得分:0)

@Sushanth的解决方案是最优化的:

import collections

lst = [1,1,2,2,3,4,4,4]

dct = collections.Counter(lst)
print(dct)