python列表操作使用示例分享

yipeiwu_com6年前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语句不对齐导致报错
"""

相关文章

在win10和linux上分别安装Python虚拟环境的方法步骤

很多初学者会使用windows作为开发机使用, 今天就来看下如何在win10和Linux下分别安装Python虚机环境。虚机环境有非常多的优点,今天我们用的虚拟环境是virtualenv...

Python实现模拟登录网易邮箱的方法示例

本文实例讲述了Python实现模拟登录网易邮箱的方法。分享给大家供大家参考,具体如下: #coding:utf-8 import urllib2,urllib import cook...

Python的标准模块包json详解

引言 对于做web开发的人来说,json文本必须要熟知与熟练使用的。大部分网站的API接口调用返回的数据,就是json格式的。如果看json对象所包含的内容,相信对熟悉Python的人开...

python内存监控工具memory_profiler和guppy的用法详解

python2.7在内存管理上相比python3还是有些坑的,其释放后的内存仍然保留在python的内存池中,不被系统所用。python循环引用的变量不会被回收,这会导致程序越运行,占用...

wxPython:python首选的GUI库实例分享

wxPython:python首选的GUI库实例分享

wxPython是Python语言的一套优秀的GUI图形库,允许Python程序员很方便的创建完整的、功能健全的GUI用户界面。 wxPython是作为优秀的跨平台GUI库wxWidge...