回顾一下以前的笔记,便于以后的查看,以ANSA二次开发作为基础,记录下用到的基础知识。字符串、列表、字典将以修改part的名字为例进行演示。importansafromansaimportbasefromansaimportconstantspart=base.GetFirstEntity(constants.NASTRAN,"ANSAPART")vals=('Name','ModuleId')ret=base.GetEntityCardValues(constants.NASTRAN,part,fields=vals)oldname=ret['Name']print(oldname)#固定字符串,测试时可以将该行注释s="HWCOLORPROP100119924"keys=s.split()my_dict={key:indexforindex,keyinenumerate(keys)}print(my_dict)str_from_dict=""forkey,valueinmy_dict.items():str_from_dict+=f"{key}{value}"print(str_from_dict)#HWCOLOR0PROP110011992243vals={'Name':str_from_dict,}#ANSA命名是会自动将首位的空格字符移除base.SetEntityCardValues(constants.NASTRAN,part,vals)这是基础的修改代码,后续皆可使用上述代码进行测试我们需要将字符串"HWCOLORPROP100119924"转换为字典形式,才能调用字典的方法。1.创建字典通过将字符串转换为字典s="HWCOLORPROP100119924"keys=s.split()my_dict={key:indexforindex,keyinenumerate(keys)}print("创建字典:",my_dict)#{'HWCOLOR':0,'PROP':1,'1001199':2,'24':3}单层字典转化为字符串my_dict={"HWCOLOR":0,"PROP":1,"1001199":2,"24":3}str_from_dict=""forkey,valueinmy_dict.items():str_from_dict+=f"{key}{value}"print(str_from_dict)#HWCOLOR0PROP1100119922432.get()方法返回指定键的值print("get()方法:",my_dict.get("HWCOLOR"))#get()方法:03.items()方法以列表返回可遍历的(键,值)元组数组print("items()方法:",list(my_dict.items()))#items()方法:[('HWCOLOR',0),('PROP',1),('1001199',2),('24',3)]4.keys()方法返回所有keyprint("keys()方法:",list(my_dict.keys()))#keys()方法:['HWCOLOR','PROP','1001199','24']5.values()方法返回所有值print("values()方法:",list(my_dict.values()))#values()方法:[0,1,2,3]6.update()方法更新字典的值my_dict.update({"NEW_KEY":4})print("update()方法:",my_dict)#update()方法:{'HWCOLOR':0,'PROP':1,'1001199':2,'24':3,'NEW_KEY':4}7.pop()方法删除字典给定键key所对应的值,返回这个值popped_value=my_dict.pop("NEW_KEY")print("pop()方法:",my_dict)#pop()方法:{'PROP':1,'1001199':2,'24':3}print("被pop出的值:",popped_value)#被pop出的值:08.popitem()方法随机返回并删除字典中的最后一对键和值popped_item=my_dict.popitem()print("popitem()方法:",my_dict)#popitem()方法:{'HWCOLOR':0,'PROP':1,'1001199':2}print("被popitem出的键值对:",popped_item)#被popitem出的键值对:('24',3)9.clear()方法清空字典my_dict.clear()10.copy()方法返回字典的浅复制my_dict_copy=my_dict.copy()print("copy()方法:",my_dict_copy)11.setdefault()方法如果键不存在于字典中,将会添加键并将值设为默认值my_dict.setdefault("NEW_KEY",None)print("setdefault()方法:",my_dict)#setdefault()方法:{'HWCOLOR':0,'PROP':1,'1001199':2,'24':3,'NEW_KEY':None}12.fromkeys()方法创建一个新字典,以序列中元素做字典的键,value为字典所有键对应的初始值new_keys=["key1","key2","key3"]new_dict=dict.fromkeys(new_keys,"default_value")print("fromkeys()方法:",new_dict)#fromkeys()方法:{'key1':'default_value','key2':'default_value','key3':'default_value'}来源:TodayCAEer