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字符编码

前言 对于很多接触Python的人而言,字符的处理和语言整体的温顺可靠相比显得格外桀骜不驯难以驾驭。 文章针对Python 2.7,主要因为3对的编码已经有了很大的改善并且实际原理一样,...

Python实现图片尺寸缩放脚本

最近由于网站对图片尺寸的需要,用python写了个小脚本,方便进行图片尺寸的一些调整,特记录如下: # coding=utf-8 import Image import shut...

Python 列表理解及使用方法

Python 列表理解及使用方法 列表是最常用的Python最常用的数据类型,它和其它序列一样,可以进行包括索引,切片,加,乘,检查成员的操作。列表的数据项不需要具有相同的类型,将数据项...

Python __setattr__、 __getattr__、 __delattr__、__call__用法示例

getattr `getattr`函数属于内建函数,可以通过函数名称获取 复制代码 代码如下: value = obj.attribute value = getattr(obj, "a...

详解Python中的format格式化函数的使用方法

详解Python中的format格式化函数的使用方法

format函数实现字符串格式化的功能 基本语法为: 通过 : 和 {} 来控制字符串的操作 一、对字符串进行操作 1. 不设置指定位置,按默认顺序插入 ①当参数个数等于{}个数的时候...