[入门-1]基础类型之列表

本文详细介绍Python中列表的各种操作,包括创建、访问、增删改查等基础操作,并讲解了比较、切片、成员关系等操作符的应用。此外还介绍了内建函数及列表类型的特有方法,如排序、反转等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

基础操作

#create
aList = [123, 'abc', [123, 4.45, 'hello'], 7-9j]
bList = []
list('foo')
#access
aList[0]
aList[2][1]
aList[0:2]
#remove add delete
[].append()
[].remove()
del aList[1]
del aList

操作符

#compare
>
<
==
#切片, same as 序列类型操作符

#成员关系
123 in aList
'abc' not in aList
#连接操作符
+
list.extend()
#重复操作符
*
aList*2
#列表解析
[i for i in range(8) if i%2 ==  0]   [0, 2 ,4, 6]
[exp for var in [] if var_exp]

内建函数

#标准类型内建函数
cmp(list1,list2)
#序列内建函数
len()
max()/min()
sorted()  #字典序,ASCII序
reversed()
enumerate()
for i, item in enumerate(aList)
    print i, item
zip()
for i,j in zip(aList,bList)
    print ('%s %s' % (i, j)).title()
sum(aList)
sum(aList,5)
reduce(operator.add, aList)

anotherList = list(aTuple)
anotherTuple = tuple(aList)
[id(x) for x in aList, aTuple, anotherList, anotherTuple]

列表类型内建函数

dir(list)
dir([])

list.append(obj)   #add at tail
list.count(obj)    #返回obj出现的次数
list.extend(seq)   #原地,序列seq/可迭代对象的内容加入list

list.index(obj,i=0,j=len(list)) #返回list[key]==obj的key值,key范围可以选定
#Notice index之前先用in来判断是否在列表中,否则index会返回异常
list.insert(index,obj)          #索引位置插入obj
list.pop(index=-1)              #删除并返回指定对象
list.remove(obj)                #删除obj
list.reverse()                  #原地,翻转列表
list.sort(func=None,key=None,reverse=False) #原地排序
#Notice,原地的意思是无返回值

example

#!/usr/bin/python

stack = []
def pushit():
    pass
def popit():
    pass
def viewstack():
    pass

CMDs={'u':pushit, 'o':popit, 'v':viewstack}

def showmenu():
    pr='''
    p(U)sh
    p(O)p
    (V)iew
    (Q)uit

    Enter choice:'''

    while True:
        while True:
            try:
                choice = raw_input(pr).strip().lower()
            except (EOFError, KeyboardInterrupt, IndexError):
                choice = 'q'

            print '\n You picked: [%s]' % choice
            if choice not in 'uovq'
                print 'Invalid option, try again'
            else:
                break
        if choice == 'q'
            break
        CMDs[choice]()

if __name__ == '__main__'
    showmenu()

Reference

Python核心编程

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值