python学习list笔记
List(列表) 是 Python 中使用最频繁的数据类型;
支持字符,数字,字符串甚至可以包含列表(所谓嵌套)
1、定义:
list = [1,3,4,5,’goog’,’well’,777]
2、从最后一列增加:
list.append(“your are good!”)
显示:
直接输入:list
显示:[1, 3, 4, 5, ‘goog’, ‘well’, 777, ‘your are good!’]
3、从中间增加一列如:
使用:insert函数:
使用方法如下:
>>> list.insert(8,’liwen’)
>>> list
[1, 3, 4, 5, ‘goog’, ‘liwen’, ‘well’, ‘liwen’, ‘liwen’, 777, ‘your are good!’]
4、删除一个:
使用del
如:
>>> list
[1, 3, 4, 5, ‘goog’, ‘liwen’, ‘well’, ‘liwen’, ‘liwen’, 777, ‘your are good!’]
>>> del list[1] #删除下标为第一个的值
>>> list
[1, 4, 5, ‘goog’, ‘liwen’, ‘well’, ‘liwen’, ‘liwen’, 777, ‘your are good!’]
5、遍历全部值:
list = [1, 4, 5, ‘goog’, ‘liwen’, ‘well’, ‘liwen’, ‘liwen’, 777, ‘your are good!’]
使用for循环遍历:
for i in list:
print i
6、查看list长度使用len函数
list = [1, 4, 5, ‘goog’, ‘liwen’, ‘well’, ‘liwen’, ‘liwen’, 777, ‘your are good!’]
print len(list)
print ‘=====================’
a = ‘ddddddddddddddddddd’
print len(a)
10
=====================
19
=====================
7、计算:统计5出现了几次:
c = [1,3,4,5,5,5,5,5,4,5,4,6,9]
ncount = 0
for i in c:
if i == 5:
ncount = ncount + 1
print ncount
结果:
6
==========ncount===========
偶数与奇数:
range(1,101,2) 奇数
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23,25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63,65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99]
range(2,101,2) 偶数
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26,28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66,68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100]
补充:
1、
#!/usr/bin/env python
# -*- coding: utf-8 -*-
if __name__ == ‘__main__’:
list = [‘html’, ‘js’, ‘css’, ‘python’]
# 方法1
print u’遍历列表方法1:’
for i in list:
print (u”序号:%s 值:%s” % (list.index(i) + 1, i))
print u’/n遍历列表方法2:’
# 方法2
for i in range(len(list)):
print (u”序号:%s 值:%s” % (i + 1, list[i]))
# 方法3
print u’/n遍历列表方法3:’
for i, val in enumerate(list):
print (u”序号:%s 值:%s” % (i + 1, val))
# 方法3
print u’/n遍历列表方法3 (设置遍历开始初始位置,只改变了起始序号):’
for i, val in enumerate(list, 2):
print (u”序号:%s 值:%s” % (i + 1, val))
原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/tech/opensource/193063.html