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数据结构之图深度优先和广度优先用法。分享给大家供大家参考。具体如下: 首先有一个概念:回溯   回溯法(探索与回溯法)是一种选优搜索法,按选优条件向前搜索,以达...

Pandas 同元素多列去重的实例

有一些问题可能会遇到同元素多列去重问题,下面介绍一种非常简单效率也很快的做法,用pandas来实现。 首先我们看一下数据类型: G1 G2 a b b a c d d c e f...

Python RuntimeError: thread.__init__() not called解决方法

在写一个多线程类的时候调用报错 RuntimeError: thread.__init__() not called 复制代码 代码如下: class NotifyTread(thre...

Python中规范定义命名空间的一些建议

API的设计是一个艺术活。往往需要其简单、易懂、整洁、不累赘。 很多时候,我们在底层封装一个方法给高层用,而其它的方法只是为了辅助这个方法的。 也就是说我们只需要暴露这个方法就行,不用关...

Python列表推导式的使用方法

1.列表推导式书写形式:   [表达式 for 变量 in 列表]    或者  [表达式 for 变量 in 列表 if 条件] 2.举例说明:...