回顾一下以前的笔记,便于以后的查看,以ANSA二次开发作为基础,记录下用到的基础知识。
字符串、列表、字典将以修改part的名字为例进行演示。
import ansa
from ansa import base
from ansa import constants
part = base.GetFirstEntity(constants.NASTRAN,"ANSAPART")
vals = ('Name', 'Module Id')
ret = base.GetEntityCardValues(constants.NASTRAN,part, fields=vals)
oldname = ret['Name']
print (oldname)
# 固定字符串,测试时可以将该行注释
s = "HWCOLOR PROP 1001199 24"
keys = s.split()
my_dict = {key: index for index, key in enumerate(keys)}
print(my_dict)
str_from_dict = ""
for key, value in my_dict.items():
str_from_dict += f"{key} {value} "
print(str_from_dict) #HWCOLOR 0PROP 11001199 224 3
vals = {'Name':str_from_dict,}
# ANSA命名是会自动将首位的空格字符移除
base.SetEntityCardValues(constants.NASTRAN, part, vals)
这是基础的修改代码,后续皆可使用上述代码进行测试
s = "HWCOLOR PROP 1001199 24"
keys = s.split()
my_dict = {key: index for index, key in enumerate(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 = ""
for key, value in my_dict.items():
str_from_dict += f"{key} {value}"
print(str_from_dict) #HWCOLOR 0PROP 11001199 224 3
print("get()方法:", my_dict.get("HWCOLOR"))
#get()方法: 0
print("items()方法:", list(my_dict.items()))
#items()方法: [('HWCOLOR', 0), ('PROP', 1), ('1001199', 2), ('24', 3)]
print("keys()方法:", list(my_dict.keys()))
#keys()方法: ['HWCOLOR', 'PROP', '1001199', '24']
print("values()方法:", list(my_dict.values()))
#values()方法: [0, 1, 2, 3]
my_dict.update({"NEW_KEY": 4})
print("update()方法:", my_dict)
#update()方法: {'HWCOLOR': 0, 'PROP': 1, '1001199': 2, '24': 3, 'NEW_KEY': 4}
popped_value = my_dict.pop("NEW_KEY")
print("pop()方法:", my_dict)
#pop()方法: {'PROP': 1, '1001199': 2, '24': 3}
print("被pop出的值:", popped_value)
#被pop出的值: 0
popped_item = my_dict.popitem()
print("popitem()方法:", my_dict)
#popitem()方法: {'HWCOLOR': 0, 'PROP': 1, '1001199': 2}
print("被popitem出的键值对:", popped_item)
#被popitem出的键值对: ('24', 3)
my_dict.clear()
my_dict_copy = my_dict.copy()
print("copy()方法:", my_dict_copy)
my_dict.setdefault("NEW_KEY", None)
print("setdefault()方法:", my_dict)
#setdefault()方法: {'HWCOLOR': 0, 'PROP': 1, '1001199': 2, '24': 3, 'NEW_KEY': None}
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'}