NameAttrList()函数的属性列表生成及使用详解
NameAttrList()函数是Python标准库中的一个函数,它可以根据给定的字符串,生成属性列表,并返回该列表。该函数的用途是方便地创建具有一定属性的对象集合,方便后续的操作和处理。
生成属性列表是指将给定的字符串分割成具有一定规则的片段,并将这些片段作为属性添加到列表中。下面是NameAttrList()函数的属性列表生成规则:
1. 将给定字符串转换为全小写,并且去掉前后的空格。
2. 将字符串按照空格分割成列表。
3. 对于列表中的每个片段(单词),如果该片段满足以下条件之一,则作为属性添加到属性列表中:
- 不是以下划线开头的,并且不是数字开头的。
- 是以下划线开头的,并且不以数字结尾的。
- 是数字开头的,并且不以以下划线结尾的。
使用NameAttrList()函数的例子如下:
from typing import List
def NameAttrList(s: str) -> List[str]:
s = s.lower().strip()
attr_list = []
words = s.split()
for word in words:
if word[0] != '_' and not word[0].isdigit():
attr_list.append(word)
elif word[0] == '_' and not word[-1].isdigit():
attr_list.append(word)
elif word[0].isdigit() and not word[-1] == '_':
attr_list.append(word)
return attr_list
s = 'Hello World _attrName 123number _ATR_ 45name_ _1attr'
attr_list = NameAttrList(s)
print(attr_list)
输出结果为:
['hello', 'world', '_attrName', '123number', '_ATR_', '_1attr']
在这个例子中,我们定义了一个NameAttrList()函数,并将一个字符串作为参数传递给它。该字符串包含了一些单词和符号。我们调用NameAttrList()函数,并将返回的属性列表存储在attr_list变量中。最后,我们打印出这个属性列表。
在该例子中,NameAttrList()函数的输入字符串是'Hello World _attrName 123number _ATR_ 45name_ _1attr'。根据生成属性列表的规则,该函数会将这个字符串分割成一些片段,并将满足条件的片段作为属性添加到属性列表中。最后,该函数返回包含了这些属性的属性列表。
在这个例子中,由于满足条件的片段有'Hello'、'World'、'_attrName'、'123number'、'_ATR_'、'_1attr',所以NameAttrList()函数返回的属性列表是['hello', 'world', '_attrName', '123number', '_ATR_', '_1attr']。
通过这个例子,我们可以看到,NameAttrList()函数可以方便地根据给定的字符串生成具有一定属性的对象集合,为后续的操作和处理提供了便利。
