多字典时间复杂度体系结构

2024-04-26 18:01:56 发布

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

我想知道是否有人愿意帮助我为以下目标确定最有效的时间复杂度方法:

我想打印一个全面的和非冗余的清单,结果从3字典。我还希望字典之间匹配的条目合并到一行,如果不匹配,则用“NA”填充这些条目。目前为止,我的方法如下:

for key in dict1:
    if key in dict2 and key in dict3:
        output.write(str(dict1[key][0]) + "\t" + str(dict2[key][0]) + "\t" + str(dict3[key][0]))
    elif key not in dict2 and key in dict3:
        output.write(str(dict1[key][0]) + "\t" + "NA" + "\t" + str(dict3[key][0]))
    elif key in dict2 and key not in dict3:
        output.write(str(dict1[key][0]) + "\t" + str(dict2[key][0]) + "\t" + "NA")
    else:
        output.write(str(dict1[key][0]) + "\t" + "NA" + "\t" + "NA")
for key in dict2:    
    if key not in dict1 and key in dict3:
        output.write("NA" + "\t" + str(dict2[key][0]) + "\t" + str(dict3[key][0]))
    elif key not in dict1 and key not in dict3:
        output.write("NA" + "\t" + str(dict2[key][0]) + "\t" + "NA")   
for key in dict3:
    if key not in dict2 and key not in dict3:
        output.write("NA" + "\t" + "NA" + "\t" + str(dict3[key][0]))

我觉得有一个更有效的方法(在时间复杂性方面)来构建这个。我正在与大文件和任何帮助将不胜感激,以帮助我加快我的代码。我是计算机科学的新手,所以如果有可能的话,我想避免使用额外的软件包(不过还是很感激这些提示!)并专注于基本架构,以确保我在前进的过程中具备强大的基本技能。你知道吗


Tags: and方法keyinforoutputifnot
1条回答
网友
1楼 · 发布于 2024-04-26 18:01:56

就复杂性而言,这里没有什么可以改进的。你在一个接一个地排除可能性,这真的是你能走的最快的速度。你知道吗

每个键和字典只能进行一次成员身份检查,但是字典中的成员身份检查是O(1),所以我怀疑这会影响您的性能。你知道吗

不过,Python确实有pandas模块,它只需一行代码就可以满足您的需要:

脚本:

first=dict(a=1,b=3,c=5)
second=dict(d=1,b=5,f=5)
third=dict(f=1,q=3,a=5)
import pandas as pd
df=pd.DataFrame.from_dict(dict(first=first,second=second,third=third),)
print(df)

输出:

   first  second  third
a    1.0     NaN    5.0
b    3.0     5.0    NaN
c    5.0     NaN    NaN
d    NaN     1.0    NaN
f    NaN     5.0    1.0
q    NaN     NaN    3.0

相关问题 更多 >