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

相关文章

Windows下Python2与Python3两个版本共存的方法详解

Windows下Python2与Python3两个版本共存的方法详解

前言 一向用Python 3,最近研究微信公众号开发,各云平台只支持Python 2.7,想用其他版本需要自己搭建环境。而网上又搜不到Python 3开发微信公众号的资料。暂打算先使用P...

Python 查找list中的某个元素的所有的下标方法

如下所示: #!/usr/bin/env python #_*_ coding:utf-8 _*_ name = ['hello', 'world', 'a', 'b', 'c',...

使用PyInstaller将python转成可执行文件exe笔记

1、安装PyInstaller PyInstaller的作用如标题所说,首先需要下载PyInstaller和UPX,UPX是用来压缩exe的,点击超链接下载吧,目前稳定版本是1.3,注意...

详谈套接字中SO_REUSEPORT和SO_REUSEADDR的区别

Socket的基本背景 在讨论这两个选项的区别时,我们需要知道的是BSD实现是所有socket实现的起源。基本上其他所有的系统某种程度上都参考了BSD socket实现(或者至少是其接口...

Python中常用的内置方法

Python中常用的内置方法

1.最大值 max(3,4) ##运行结果为4 2.最小值 min(3,4) ##运行结果为3 3.求和 sum(range(1,101)) ##求1~100的和...