搜尋
首頁後端開發Python教學python开发之list操作实例分析

本文实例分析了python开发之list操作。分享给大家供大家参考,具体如下:

对python中list的操作,大家可以参考《Python list操作用法总结》

以下是我个人的笔记:

#python list
'''
  创建list有很多方法:
  1.使用一对方括号创建一个空的list:[]
  2.使用一对方括号,用','隔开里面的元素:[a, b, c], [a]
  3.Using a list comprehension:[x for x in iterable]
  4.Using the type constructor:list() or list(iterable)
'''
def create_empty_list():
  '''Using a pair of square brackets to denote the empty list: [].'''
  return []
def create_common_list():
  '''Using square brackets, separating items with commas: [a], [a, b, c].'''
  return ['a', 'b', 'c', 1, 3, 5]
def create_common_list2():
  '''Using a list comprehension: [x for x in iterable].'''
  return [x for x in range(1, 10)]
def str_to_list(s):
  '''Using a string to convert list'''
  if s != None:
    return list(s)
  else:
    return []
def main():
  test_listA = create_empty_list()
  print(test_listA)
  print('#' * 50)
  test_listB = create_common_list()
  print(test_listB)
  print('#' * 50)
  test_listC = create_common_list2()
  print(test_listC)
  print('#' * 50)
  test_str = 'i want to talk about this problem!'
  test_listD = str_to_list(test_str)
  print(test_listD)
if __name__ == '__main__':
  main()

运行效果:

Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>> 
[]
##################################################
['a', 'b', 'c', 1, 3, 5]
##################################################
[1, 2, 3, 4, 5, 6, 7, 8, 9]
##################################################
['i', ' ', 'w', 'a', 'n', 't', ' ', 't', 'o', ' ', 't', 'a', 'l', 'k', ' ', 'a', 'b', 'o', 'u', 't', ' ', 't', 'h', 'i', 's', ' ', 'p', 'r', 'o', 'b', 'l', 'e', 'm', '!']
>>> 

下面有更多的demo:

Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> counter = 100
>>> miles = 1000.0
>>> name = "hongten"
>>> numberA,numberB,nameC = 1,2,"Hongten"
>>> list = [counter,miles,name,numberA,numberB,nameC]
>>> print(list)
[100, 1000.0, 'hongten', 1, 2, 'Hongten']
>>> #这是注释部分,注释用"#"开始
>>> for element in list:
  print(element)
100
1000.0
hongten
1
2
Hongten
>>> #上面是遍历列表list
>>> print(list[0]) #获取列表list里面的第一个元素值
100
>>> print(list[-1]) #获取列表list里面的最后一个元素值
Hongten
>>> print(len(list)) #用len(list)获取list列表的长度
6
>>> num_inc_list = range(10) #产生一个数值递增的列表
>>> print(num_inc_list)
range(0, 10)
>>> for inc_list in num_inc_list:
  print(inc_list)
0
1
2
3
4
5
6
7
8
9
>>> #从这里我们可以看到range(10)是产生了一个从0开始到9的一个数值递增列表
>>> initial_value = 10
>>> list_length = 5
>>> myList = [initial_value for i in range(10)]
>>> print(myList)
[10, 10, 10, 10, 10, 10, 10, 10, 10, 10]
>>> list_length = 2
>>> myList = myList * list_length
>>> print(myList)
[10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10]
>>> print(len(myList))
20
>>> #上面是用一个固定值initial_value去初始化一个列表myList
>>> #同时用myList = myList * list_length去复制myList
>>> #下面再看看复制的效果
>>> copyList = [1,2,3,"hongten"]
>>> copyList = copyList * list_length
>>> print(len(copyList))
8
>>> for cl in copyList:
  print(cl)
1
2
3
hongten
1
2
3
hongten
>>> #下面我们来仔细研究一下python里面的list
>>> #在一个list中可以包含不同类型的元素,这个和ActionScript 3.0(AS3.0)中的数组类似
>>> test_list = ["hello",1,2,"world",4,5,"hongten"]
>>> print(len(test_list))
7
>>> print(test_list[0]) # 打印test_list
hello
>>> #打印test_list中的第一元素
>>> print(test_list[-1]) #打印test_list中最后一个元素
hongten
>>> print(test_list[-len]) #打印第一个元素
Traceback (most recent call last):
 File "<pyshell#44>", line 1, in <module>
  print(test_list[-len]) #打印第一个元素
TypeError: bad operand type for unary -: 'builtin_function_or_method'
>>> print(test_list[-len(test_list)]) #打印第一个元素
hello
>>> print(test_list[len(test_list) - 1]) #打印最后一个元素
hongten
>>> test_list.append(6) #向列表中追加一个元素
>>> print(test_list[-1])
6
>>> test_list.insert(1,0)
>>> print(test_list)
['hello', 0, 1, 2, 'world', 4, 5, 'hongten', 6]
>>> #上面的操作是向列表test_list的小标为1的地方插入元素0
>>> test_list.insert(1,0)
>>> print(test_list)
['hello', 0, 0, 1, 2, 'world', 4, 5, 'hongten', 6]
>>> test_list.insert(2,1)
>>> print(test_list)
['hello', 0, 1, 0, 1, 2, 'world', 4, 5, 'hongten', 6]
>>> print(test_list.pop(0)) #返回最后一个元素,并从test_list中删除之
hello
>>> print(test_list)
[0, 1, 0, 1, 2, 'world', 4, 5, 'hongten', 6]
>>> print(test_list.pop(2)) #上面的注释有错误,pop(index)的操作是返回数组下标为index的元素,并从列表中删除之
0
>>> print(test_list)
[0, 1, 1, 2, 'world', 4, 5, 'hongten', 6]
>>> test_list.remove(1)
>>> print(test_list)
[0, 1, 2, 'world', 4, 5, 'hongten', 6]
>>> #remove(1)表示的是删除第一次出现的元素1
>>> test_list.insert(0,1)
>>> print(test_list)
[1, 0, 1, 2, 'world', 4, 5, 'hongten', 6]
>>> test_list.remove(1)
>>> print(test_list)
[0, 1, 2, 'world', 4, 5, 'hongten', 6]
>>> test_list.insert(2,"hongten")
>>> print(test_list)
[0, 1, 'hongten', 2, 'world', 4, 5, 'hongten', 6]
>>> test_list.count("hongten")
2
>>> #count(var)是统计var元素在列表中出现的个数
>>> test_list.count("foo")
0
>>> test_list_extend = ["a","b","c"]
>>> test_list.extend(test_list_extend)
>>> print(test_list)
[0, 1, 'hongten', 2, 'world', 4, 5, 'hongten', 6, 'a', 'b', 'c']
>>> #使用extend(list)作用是追加一个list到源list上面
>>> print(test_list.sort())
Traceback (most recent call last):
 File "<pyshell#76>", line 1, in <module>
  print(test_list.sort())
TypeError: unorderable types: str() < int()
>>> test_list_extend.append("h")
>>> test_lsit_extend.append("e")
Traceback (most recent call last):
 File "<pyshell#78>", line 1, in <module>
  test_lsit_extend.append("e")
NameError: name 'test_lsit_extend' is not defined
>>> list_a = ["e","z","o","r"]
>>> list_a.extend(test_list_extend)
>>> print(list_a)
['e', 'z', 'o', 'r', 'a', 'b', 'c', 'h']
>>> print(list_a.sort()) #对list_a列表进行排序
None
>>> #不知道为什么以上排序都有报错......
>>> list_b = [1,3,5,2,6,4]
>>> print(list_b.sort())
None
>>> print(sort(list_b))
Traceback (most recent call last):
 File "<pyshell#86>", line 1, in <module>
  print(sort(list_b))
NameError: name 'sort' is not defined
>>> #不去管排序问题了,先看看删除操作吧!!!!!
>>> print(list_b)
[1, 2, 3, 4, 5, 6]
>>> print(del list_b[1])
SyntaxError: invalid syntax
>>> del list_b[1]
>>> print(list_b)
[1, 3, 4, 5, 6]
>>> del list_b[0,2]
Traceback (most recent call last):
 File "<pyshell#92>", line 1, in <module>
  del list_b[0,2]
TypeError: list indices must be integers, not tuple
>>> del list_b[0:2]
>>> print(list_b)
[4, 5, 6]
>>> #del list[index]删除下标为index的元素,del list[start:end]删除从start下标开始到end下标结束的元素
>>> del list_b[10]
Traceback (most recent call last):
 File "<pyshell#96>", line 1, in <module>
  del list_b[10]
IndexError: list assignment index out of range
>>> #如果我们删除的下标超出了列表的长度范围,就会报错啦!!!!!
>>> ##########################################################################
>>> list_c = range(5);
>>> for c in list_c:
  print(c)
0
1
2
3
4
>>> list_d = list_c
>>> for d in list_d:
  print(d)
0
1
2
3
4
>>> #上面是列表的复制
>>> list_d[2] = 23
Traceback (most recent call last):
 File "<pyshell#108>", line 1, in <module>
  list_d[2] = 23
TypeError: 'range' object does not support item assignment
>>> list_e = [1,2,3,4,5]
>>> list_f = list_e
>>> list_f[2] = 234
>>> print(list_e)
[1, 2, 234, 4, 5]
>>> #从这里我们可以知道,list_f复制了list_e,list_f是对list_e的一个引用,
>>> #他们共同指向一个对象:[1,2,3,4,5],当我们视图修改list_f[2]的值的时候,
>>> #list_f所指向的对象的行为发生了变化,即元素值发生了变化,但是他们的引用是没有
>>> #发生变化的。所以list_e[2] = 234也是在情理之中。
>>> #######################################################################
>>> list_i = list_e[:]
>>> print(list_i)
[1, 2, 234, 4, 5]
>>> print(list_e)
[1, 2, 234, 4, 5]
>>> list_i[2] = 3
>>> print(list_e)
[1, 2, 234, 4, 5]
>>> print(list_i)
[1, 2, 3, 4, 5]
>>> #上面是进行了列表的克隆操作,即拷贝了另一个列表,这样的操作,会创造出新的一个列表对象
>>> #使得list_i和list_e指向不同的对象,就有着不同的引用,所以当list_i[2] = 3的时候,
>>> #list_e[2]还是等于234,即不变
>>>

希望本文所述对大家Python程序设计有所帮助。

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
學習Python:2小時的每日學習是否足夠?學習Python:2小時的每日學習是否足夠?Apr 18, 2025 am 12:22 AM

每天學習Python兩個小時是否足夠?這取決於你的目標和學習方法。 1)制定清晰的學習計劃,2)選擇合適的學習資源和方法,3)動手實踐和復習鞏固,可以在這段時間內逐步掌握Python的基本知識和高級功能。

Web開發的Python:關鍵應用程序Web開發的Python:關鍵應用程序Apr 18, 2025 am 12:20 AM

Python在Web開發中的關鍵應用包括使用Django和Flask框架、API開發、數據分析與可視化、機器學習與AI、以及性能優化。 1.Django和Flask框架:Django適合快速開發複雜應用,Flask適用於小型或高度自定義項目。 2.API開發:使用Flask或DjangoRESTFramework構建RESTfulAPI。 3.數據分析與可視化:利用Python處理數據並通過Web界面展示。 4.機器學習與AI:Python用於構建智能Web應用。 5.性能優化:通過異步編程、緩存和代碼優

Python vs.C:探索性能和效率Python vs.C:探索性能和效率Apr 18, 2025 am 12:20 AM

Python在開發效率上優於C ,但C 在執行性能上更高。 1.Python的簡潔語法和豐富庫提高開發效率。 2.C 的編譯型特性和硬件控制提升執行性能。選擇時需根據項目需求權衡開發速度與執行效率。

python在行動中:現實世界中的例子python在行動中:現實世界中的例子Apr 18, 2025 am 12:18 AM

Python在現實世界中的應用包括數據分析、Web開發、人工智能和自動化。 1)在數據分析中,Python使用Pandas和Matplotlib處理和可視化數據。 2)Web開發中,Django和Flask框架簡化了Web應用的創建。 3)人工智能領域,TensorFlow和PyTorch用於構建和訓練模型。 4)自動化方面,Python腳本可用於復製文件等任務。

Python的主要用途:綜合概述Python的主要用途:綜合概述Apr 18, 2025 am 12:18 AM

Python在數據科學、Web開發和自動化腳本領域廣泛應用。 1)在數據科學中,Python通過NumPy、Pandas等庫簡化數據處理和分析。 2)在Web開發中,Django和Flask框架使開發者能快速構建應用。 3)在自動化腳本中,Python的簡潔性和標準庫使其成為理想選擇。

Python的主要目的:靈活性和易用性Python的主要目的:靈活性和易用性Apr 17, 2025 am 12:14 AM

Python的靈活性體現在多範式支持和動態類型系統,易用性則源於語法簡潔和豐富的標準庫。 1.靈活性:支持面向對象、函數式和過程式編程,動態類型系統提高開發效率。 2.易用性:語法接近自然語言,標準庫涵蓋廣泛功能,簡化開發過程。

Python:多功能編程的力量Python:多功能編程的力量Apr 17, 2025 am 12:09 AM

Python因其簡潔與強大而備受青睞,適用於從初學者到高級開發者的各種需求。其多功能性體現在:1)易學易用,語法簡單;2)豐富的庫和框架,如NumPy、Pandas等;3)跨平台支持,可在多種操作系統上運行;4)適合腳本和自動化任務,提升工作效率。

每天2小時學習Python:實用指南每天2小時學習Python:實用指南Apr 17, 2025 am 12:05 AM

可以,在每天花費兩個小時的時間內學會Python。 1.制定合理的學習計劃,2.選擇合適的學習資源,3.通過實踐鞏固所學知識,這些步驟能幫助你在短時間內掌握Python。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
1 個月前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
1 個月前By尊渡假赌尊渡假赌尊渡假赌
威爾R.E.P.O.有交叉遊戲嗎?
1 個月前By尊渡假赌尊渡假赌尊渡假赌

熱工具

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版