python之列表(List)介绍与循环遍历
1、创建列表:In [13]: list1=[123,34,56]In [14]: list2=["zhang","qing",'hahah']In [15]: list3=["zhang",123,"qing",234]In [16]: list4=["zhang123","123zhang",123,344]In [17]: list5=["zhang123",1123,123zhang] File "<ipython-input-17-f6f00b6fdc24>", line 1 list5=["zhang123",1123,123zhang] ^SyntaxError: invalid syntax使用中括号,且用逗号把不同的数据分开即可。
2、列表中的值:列表之格式:str=['zhang','chong',12,34]使用下标索引访问列表中的值,以0开始。例如:In [49]: str1=["123","zhang","123zhang",123,345]In [50]: str1Out[50]: ['123', 'zhang', '123zhang', 123, 345]In [51]: str1[0]Out[51]: '123'In [52]: str1[1]Out[52]: 'zhang'In [53]: str1[-1]Out[53]: 345In [54]: str1[-2]Out[54]: 123
3、根据前面的学习,大家知道字符串是不能够被修改的,所以依据字符串创建列表是很有必要的比如:In [18]: list("zha荏鱿胫协ng qing")Out[18]: ['z', 'h', 'a', 'n', 'g', ' ', 'q', 'i', 'n', 'g']In [19]: list('zhanghahah')Out[19]: ['z', 'h', 'a', 'n', 'g', 'h', 'a', 'h', 'a', 'h']In [20]: list(zhang)---------------------------------------------------------------------------NameError Traceback (most recent call last)<ipython-input-20-dfd76f282fd1> in <module>()----> 1 list(zhang)NameError: name 'zhang' is not defined
4、循环遍历之for循环===》为了更有效率的输出列表的每个数据,可以使用循环来完成示例:In [3]: list1=["zhang","qing","123",123,"zhang123"In [4]: for temp in list1: ...: print("遍历list1=%s"%temp) ...: 遍历list1=zhang遍历list1=qing遍历list1=123遍历list1=123遍历list1=zhang12
5、注意:不合法示例如下:In [5]: for temp in list1: ...: print(list1[temp]) ...: ---------------------------------------------------------------------------TypeError Traceback (most recent call last)<ipython-input-5-84f18180053e> in <module>() 1 for temp in list1:----> 2 print(list1[temp]) 3TypeError: list indices must be integers or slices, not str
6、循环之while:为了更有效率的输出列表的每个数据,可以使用循环来完成In [9]: list1=["zhang","qing","123",345In [10]: i=0In [11]: while i<len(list1): ....: print(list1[i]) ....: i+=1 ....: zhangqing123345
7、注意:In [6]: list1=["zhang","挢旗扦渌;qing",'12泌驾台佐3',345]In [7]: i=0In [8]: while i<=len(list1): ...: print(list1[i]) ...: i+=1 ...: zhangqing123345---------------------------------------------------------------------------IndexError Traceback (most recent call last)<ipython-input-8-6410fdf10b12> in <module>() 1 while i<=len(list1):----> 2 print(list1[i]) 3 i+=1 4IndexError: list index out of range