python列表操作使用示例分享

yipeiwu_com5年前Python基础

复制代码 代码如下:

Python 3.3.4 (v3.3.4:7ff62415e426, Feb 10 2014, 18:13:51) [MSC v.1600 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> cast=["cleese","palin","jones","idle"]
>>> print(cast)
['cleese', 'palin', 'jones', 'idle']
>>> print(len(cast))#显示数据项数量
4
>>> print(cast[1])#显示列表中第2个数据项的值
palin
>>> cast.append("gilliam")#在列表末尾添加一个数据项
>>> print(cast)
['cleese', 'palin', 'jones', 'idle', 'gilliam']
>>> cast.pop()#删除列表末尾的数据项
'gilliam'
>>> print(cast)
['cleese', 'palin', 'jones', 'idle']
>>> cast.extend(["gilliam","chapman"])#在列表末尾增加一个数据项集合
>>> print(cast)
['cleese', 'palin', 'jones', 'idle', 'gilliam', 'chapman']
>>> cast.remove("chapman")#删除指定的数据项
>>> print(cast)
['cleese', 'palin', 'jones', 'idle', 'gilliam']
>>> cast.insert(0,"chapman")#在指定的位置增加数据项
>>> print(cast)
['chapman', 'cleese', 'palin', 'jones', 'idle', 'gilliam']
>>>

下面是讲定义一个def函数,isinstance()函数,for in,if else等的运用以及逻辑

复制代码 代码如下:

movies=["the holy grail",1975,"terry jone & terry gilliam",91,
       ["graham chapman",
       ["michael palin","john cleese","terry gilliam",
            "eric idle","terry jones"]]]
def print_lol(the_list):#定义一种函数
        for each_item in the_list:#for in循环迭代处理列表,从列表起始位置到末尾
        if isinstance(each_item,list):#isinstance()检测each_item里每一项
                                              #是不是list类型
            print_lol(each_item)#如果是,调用函数print_lol
        else:print(each_item)#如果不是,输出这一项

print_lol(movies)#在movies列表中调用函数
"""
之前if else语句不对齐导致报错
"""

相关文章

使用Python将字符串转换为格式化的日期时间字符串

我正在尝试将字符串“20091229050936”转换为“2009年12月29日(UTC)” >>>import time >>>s = time...

django foreignkey(外键)的实现

django foreignkey(外键)的实现

foreignkey是一种关联字段,将两张表进行关联的方式,我们在dodels.py里写入要生成的两张表: class Usergroup(models.Model): uid...

python用10行代码实现对黄色图片的检测功能

本文实例讲述了python用10行代码实现对黄色图片的检测功能。分享给大家供大家参考。具体如下: 原理:将图片转换为YCbCr模式,在图片中寻找图片色值像素,如果在皮肤色值内的像素面积超...

Python中的__SLOTS__属性使用示例

看python社区大妈组织的内容里边有一篇讲python内存优化的,用到了__slots__。然后查了一下,总结一下。感觉非常有用 python类在进行实例化的时候,会有一个__dict...

通过Python 获取Android设备信息的轻量级框架

今天跟大家分享一下,如何通过Python实现一个轻量级的库来获取电脑上连接的Android设备信息,为什么说轻量呢因为整个库也就4KB,相比其他诸如Appetizer这样动辄就8MB多的...