简体   繁体   English

最后一段之后从字符串中提取字符

[英]Extract characters from string after last period

I have an orderedDict : 我有一个orderedDict

dict2.items():
[('A', <function __main__.percentile_50>),
 ('B', <function numpy.core.fromnumeric.sum>),
 ('C', <function numpy.core.fromnumeric.sum>),
 ('D', <function numpy.core.fromnumeric.mean>),
 etc...

I want to create a column that says what descriptive was used (percentile_50, sum, mean, etc.) I'm thinking of finding the last . 我想创建一个列来说明使用了什么描述性内容(percentile_50,sum,mean等),我正在考虑查找最后一个. and then grabbing the characters after it up until > . 然后抓取其后的字符,直到>为止。 So I would end up with percentile_50, sum, sum, mean, etc. . 因此,我最终得到percentile_50, sum, sum, mean, etc. Any suggestions? 有什么建议么?

If you have string in your tuples you can use split within a list comprehension : 如果您的元组中有字符串,则可以在列表推导中使用split

>>> l=[('A', '<function __main__.percentile_50>'),
...  ('B', '<function numpy.core.fromnumeric.sum>'),
...  ('C', '<function numpy.core.fromnumeric.sum>'),
...  ('D', '<function numpy.core.fromnumeric.mean>')]
>>> 
>>> [(i,j.strip('>').split('.')[-1]) for i,j in l]
[('A', 'percentile_50'), ('B', 'sum'), ('C', 'sum'), ('D', 'mean')]

But if you have function objects you can use the __name__ attribute for your function to extract the names : 但是,如果有函数对象,则可以对函数使用__name__属性来提取名称:

>>> [(i,j.__name__) for i,j in l]
[('A', 'percentile_50'), ('B', 'sum'), ('C', 'sum'), ('D', 'mean')]

One of the solutions using regex: 使用正则表达式的解决方案之一:

(?<=\.)([^.>]+)(?=>$)

See DEMO 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM