Python学习之list操作,输出、删除等

List数据输出操作,用迭代器:

函数参数l为传入的list,i为指定要出的起始位(默认值为0,即从开始输出),j为指定要输出的最后位(一般设定为len(l)

def data_cout(l,j,i=0):
    li1=iter(l)
    while i<j:
        i=i+1
        print li1.next(),
    print '\ncout finished!'
li=list('www.buaa.edu.cn')
data_cout(li,len(li))
输出结果:

w w w . b u a a . e d u . c n 

cout finished!

此函数其实也可以用于输出元组数据(tuple)

tu=(13,2424,'353fkjk',20490)
print 'tu=',tu
data_cout(tu,len(tu))
输出结果:

tu= (13, 2424, '353fkjk', 20490) 
13 2424 353fkjk 20490 
cout finish!

List字符的删除操作:

函数参数listchars为传入的字符list,s1为要删除的字符

def pop_char(listchars,s1):
    while s1 in listchars:
        listchars.pop(listchars.index(s1))
    print len(listchars)
    print listchars
def del_char(listchars,s1):
    while s1 in listchars:
        del listchars[listchars.index(s1)]
    print len(listchars)
    print listchars

def remove_char(listchars,s1):
    while s1 in listchars:
        listchars.remove(s1)
    print len(listchars)
    print listchars

这三个函数都可以对list字符的指定字符进行删除操作:


li2=list('www.buaa.edu.cn')
li3=list('www.buaa.edu.cn')
li4=list('www.buaa.edu.cn')
pop_char(li2,'.')
del_char(li3,'.')
remove_char(li4,'.')
输出结果:

12
['w', 'w', 'w', 'b', 'u', 'a', 'a', 'e', 'd', 'u', 'c', 'n']
12
['w', 'w', 'w', 'b', 'u', 'a', 'a', 'e', 'd', 'u', 'c', 'n']
12
['w', 'w', 'w', 'b', 'u', 'a', 'a', 'e', 'd', 'u', 'c', 'n']

List字符的去除非字母元素的操作:

其中s0可以定义为全局变量,对于多次调用此函数的程序,代码效率会提高很多

def only_alpha(listchars):
    s0=['!','@','#','$','%','^','&','*','(',')','_','+','0','1','2','3','4','5','6','7','8','9','-','=','{','}','|','[',']',':','"',';','<','>','?',',','.','/','\\']
    for s1 in s0:
        while s1 in listchars:
            listchars.remove(s1)
    print 'listchars.len()=',len(listchars)
    print 'listchars=',listchars

例子:

li5=list('jiiMII&^*&(445JKJIJI1213480\\{{}]]:;;,<>[]729793JIJI')
only_alpha(li5)
输出结果:
listchars.len()= 16
listchars= ['j', 'i', 'i', 'M', 'I', 'I', 'J', 'K', 'J', 'I', 'J', 'I',  'J', 'I', 'J', 'I']





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值