python:数组里有数字和单词,如何将数字去掉

Python023

python:数组里有数字和单词,如何将数字去掉,第1张

方法一、利用正则表达式

用法:

## 总结## ^ 匹配字符串的开始。## $ 匹配字符串的结尾。## \b 匹配一个单词的边界。## \d 匹配任意数字。## \D 匹配任意非数字字符。## x? 匹配一个可选的 x 字符 (换言之,它匹配 1 次或者 0 次 x 字符)。## x* 匹配0次或者多次 x 字符。## x+ 匹配1次或者多次 x 字符。## x{n,m} 匹配 x 字符,至少 n 次,至多 m 次。## (a|b|c) 要么匹配 a,要么匹配 b,要么匹配 c。## (x) 一般情况下表示一个记忆组 (remembered group)。你可以利用 re.search 函数返回对象的 groups() 函数获取它的值。## 正则表达式中的点号通常意味着 “匹配任意单字符”

[plain] view plain copy

import re

string = u'127米'

print re.findall(r"\d+\.?\d*", string)

方法二、利用filter(str.isdigit, iterable)

[plain] view plain copy

string = u'127米'

print (filter(str.isdigit, string))

bug:TypeError: descriptor 'isdigit' requires a 'str' object but received a 'unicode'

原因:string不是str类型

修改为:

[plain] view plain copy

string = u'127米'

string2 = string.encode('gbk')

print (type(str))

print (filter(str.isdigit, string2))

结果:

<type 'str'>127

注意:要提取的字符串不能命名为str,否则会出现TypeError: isdigit() takes no arguments (1 given)

因为str和filter里的str重名了。

以下代码的功能是 统计列表中重复项的出现次数

这里面就用到了 count() 函数

mylist = ['apple', 'banana', 'grape', 'banana', 'apple', 'grape', 'grape']

myset = set(mylist)

for item in myset:

print("the %s has been found %d times" % (item, mylist.count(item)))

函数COUNT在计数时,将把数值型的数字计算进去;但是错误值、空值、逻辑值、日期、文字则被忽略。

如果参数是一个数组或引用,那么只统计数组或引用中的数字;数组中或引用的空单元格、逻辑值、文字或错误值都将忽略。如果要统计逻辑值、文字或错误值,请使用函数COUNTA(COUNTIF按EXCEL的说明也行,但常出毛病)。

排序过程

假设输入的线性表L的长度为n,L=L1,L2,..,Ln;线性表的元素属于有限偏序集S,|S|=k且k=O(n),S={S1,S2,..Sk};则计数排序可以描述如下:

1、扫描整个集合S,对每一个Si∈S,找到在线性表L中小于等于Si的元素的个数T(Si);

2、扫描整个线性表L,对L中的每一个元素Li,将Li放在输出线性表的第T(Li)个位置上,并将T(Li)减1。

以上内容参考:百度百科-计数排序