python 基础 1.5 python数据类型(二)--列表常用方法示例

本文详细介绍了Python中列表的基本使用方法,包括类型判断、属性获取、元素追加、索引查找、元素插入、元素移除、排序及反转等常用操作,并通过实例展示了列表切片和zip函数的应用。

#/usr/bin/python

#coding=utf-8

#@Time   :2017/10/12 23:30

#@Auther :liuzhenchuan

#@File   :列表.py

list1 = [1,2,3,4]

print type(list1)

str1 = 'abcd'

print list(str1)

print dir(list1)

>>>

 

<type 'list'>
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

 

print '###'*20

 

#append()  在末尾追加一个元素

list2 = ['a','b','c','d']

list2.append('00')

print list2

>>> ['a', 'b', 'c', 'd', '00']

 

 

#index() 用于列表中第一个匹配项的索引位置

list3 = ['heoll','world','good','ABC']

print list3.index('good')

 

print type(str(list3))

print str(list3)

print str(list3)[20]

print (str(list3)).find('good')

 

>>> 2

 

  <type 'list'>

 

  ['heoll', 'world', 'good', 'ABC']

 

  <type 'str'>

 

  g

 

  20

 

 

 

 

#insert() 用于将制定对象插入制定位置

list4 = ['abc','tty','oop']

list4.insert(1,'aa')  //在索引1的位置后插入字符aa

print list4

 

>>> ['abc', 'aa', 'tty', 'oop']

 

 

#pop() 用于移除列表中的一个元素(默认为最后一个元素),并且返回该元素的值

print list4

 

list4.pop()

list4.pop(0)

print list4

 

>>> ['abc', 'tty', 'oop']

 

  oop

 

  abc

 

  ['tty']
 
 

#remove() 用于移除列表中某个值的第一个匹配项

list4 = ['abc','tty','oop']

list4.remove('tty')

print list4

 

>>> ['abc', 'oop']

 

 

#sort() 对列表进行原址排序,既然是原址排序,那显然元祖不可能拥有这种方法,因为元祖是不可变的

x = [4,7,8,3,5,1,2,6,9]

x.sort()

print x

 

>>> [1, 2, 3, 4, 5, 6, 7, 8, 9]

 

 

#reverse()  函数用于反向列表中的元素

x1 = ['d','c','abc','ab','a','123','1']

x1.sort()

print x1

x1.reverse()

print x1

 

>>> '1', '123', 'a', 'ab', 'abc', 'c', 'd']

 

 

#切片

x1 = ['d','c','abc','ab','a','123','1']

print x1[:]

print x1[1:]

print x1[1:5]

print x1[1:6:2]

>>> 

  ['d', 'c', 'abc', 'ab', 'a', '123', '1']

 

  ['c', 'abc', 'ab', 'a', '123', '1']

 

  ['c', 'abc', 'ab', 'a']

 

  ['c', 'ab', '123']

 

 

 

#zip()函数接受多个任意(包括0和1)序列作为参数,返回一个tuple列表。可以把多个列表叠加成一个元组列表

l1 = ['a','b','c','d']

l2 = [1,2,3,4]

l3 = zip(l1,l2)

print l3

>>> [('a', 1), ('b', 2), ('c', 3), ('d', 4)]

 

转载于:https://www.cnblogs.com/lzcys8868/p/7714452.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值