列表是可变的,这是他区别于字符串和元组最重要的特点,列表可以修改,而字符串和元组不能。
(1)创建通过下面的方式创建
list=['hello,world']print listlist_number=[1,2,3]print list_number输出:
或者通过list()创建
list=list('hello world')print list输出:
使用下标索引来访问列表中的值,同样你也可以使用方括号的形式截取字符
list = ['physics', 'chemistry', 1997, 2000]list_next = [1, 2, 3, 4, 5, 6, 7 ]print "list[0]: ", list[0]print "list_next[1:5]: ", list_next[1:5]输出:
(3)更新你可以对列表的数据项进行修改或更新,你也可以使用append()方法来添加列表项
# -*- coding: UTF-8 -*- list = [] ## 空列表list.append('Google') ## 使用 append() 添加元素list.append('Runoob')print list输出:
(4)删除list = ['physics', 'chemistry', 1997, 2000] print listdel list[2]print "After deleting value at index 2 : "print list输出:
方法:
1list.append(obj)
在列表末尾添加新的对象2list.count(obj)
统计某个元素在列表中出现的次数3list.extend(seq)
在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)4list.index(obj)
从列表中找出某个值第一个匹配项的索引位置5list.insert(index, obj)
将对象插入列表6list.pop(obj=list[-1])
移除列表中的一个元素(默认最后一个元素),并且返回该元素的值7list.remove(obj)
移除列表中某个值的第一个匹配项8list.reverse()
反向列表中元素9list.sort([func])
对原列表进行排序
2.元组元组与列表一样,也是一种序列,唯一不同的是元组不能被修改(字符串其实也有这种特点)。 (1)创建
a = 1, 2, 3b = 'hello', 'world'c = (1, 2, 3, 4)d = ()e = (1,)print a, b, c, d, e
输出:
逗号分隔值,元组自动创建完成
元组大部分用圆括号括起来
空元组可以用没有包含内容的圆括号表示
只含一个值的元组,必须加个逗号(,)
tuple函数
tuple函数:以一个序列作为参数并把它作为元组。如果参数为元组,就原样返回
a = tuple([1, 2, 3])b = tuple("hello")c = tuple((1, 2, 3))print aprint bprint c字符串(1)创建my_str = 'Hello world'print my_strprint my_str[0]for c in my_str: print cprint type(my_str)
字符串的格式化my_str='Hello,%s' % 'world.'print my_str
输出:
字符串的格式化,特别是在数据库语句中还是用的挺多,用法也多样性。这个会单拎出来做专题讲
对数字进行格式化处理,通常需要控制输出的宽度和精度:
输出:
从列表、元组以及字符串可以“抽象”出序列的一些公共通用方法(不是你想像中的CRUD),这些操作包括:索引(indexing)、分片(sliceing)、加(adding)、乘(multiplying)以及检查某个元素是否属于序列的成员。除此之外,还有计算序列长度、最大最小元素等内置函数
(1)索引
str1 = 'Hello'nums = [1, 2, 3, 4]t1 = (123, 234, 345)print str1[0]print nums[1]print t1[2]H2345索引从0(从左向右)开始,所有序列可通过这种方式进行索引。神奇的是,索引可以从最后一个位置(从右向左)开始,编号是-1:
str1='Hello'nums=[1,2,3,4]t1=(123,234,345)print str1[-1]print nums[-2]print t1[-3]o3123分片分片操作用来访问一定范围内的元素。分片通过冒号相隔的两个索引来实现:
nums=range(10)print numsprint nums[1:5]print nums[6:10]print nums[1:]print nums[-3:-1]print nums[-3:] #包括序列结尾的元素,置空最后一个索引print nums[:] #复制整个序列输出
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9][1, 2, 3, 4][6, 7, 8, 9][1, 2, 3, 4, 5, 6, 7, 8, 9][7, 8][7, 8, 9]序列相加str1='Hello'str2=' world'print str1+str2num1=[1,2,3]num2=[2,3,4]print num1+num2print str1+num1输出
Hello world[1, 2, 3, 2, 3, 4]乘法print [None]*10str1='Hello'print str1*2num1=[1,2]print num1*2print str1*num1输出
[None, None, None, None, None, None, None, None, None, None]HelloHello[1, 2, 1, 2]Traceback (most recent call last): print str1*num1TypeError: can't multiply sequence by non-int of type 'list' 成员资格in运算符会用来检查一个对象是否为某个序列(或者其他类型)的成员(即元素):
str1='Hello'print 'h' in str1 print 'H' in str1num1=[1,2]print 1 in num1FalseTrueTrue长度、最大最小值通过内建函数len、max和min可以返回序列中所包含元素的数量、最大和最小元素。
str1='Hello'print len(str1) print max(str1)print min(str1)num1=[1,2,1,4,123]print len(num1) print max(num1)print min(num1)输出
5oH51231未完待续。。。
接下来会更新字典内容
本文感谢Jeff Wong的博客文章点击打开链接,菜鸟教程点击打开链接