您好,登錄后才能下訂單哦!
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))
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。