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验证码识别的示例代码

写爬虫有一个绕不过去的问题就是验证码,现在验证码分类大概有4种: 图像类 滑动类 点击类 语音类 今天先来看看图像类,这类验证码大多是数字、字母的组合,国内也有使用汉...

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

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

在Django的视图中使用form对象的方法

在学习了关于Form类的基本知识后,你会看到我们如何把它用到视图中,取代contact()代码中不整齐的部分。 一下示例说明了我们如何用forms框架重写contact(): # v...

微信公众号token验证失败解决方案

我用的是python3+,而官网给的例子是python2的写法。问题就在python版本不同。 下面是截取官方的实例代码的一部分 list = [token, timestamp,...

利用Python开发微信支付的注意事项

利用Python开发微信支付的注意事项

前言 微信支付是由微信及财付通联合推出的移动支付创新产品。如今,随着微信支付的全面开放,相关需求也越来越多,很多开发人员进行微信支付开发及商家申请微信支付时,面临着诸多疑惑。 要想开发顺...