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]: str1
Out[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]: 345
In [54]: str1[-2]
Out[54]: 123

3、根据前面的学习,大家知道字符串是不能够被修改的,所以依据字符串创建列表是很有必要的
比如:
In [18]: list("zhang 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=0
In [11]: while i<len(list1):
....: print(list1[i])
....: i+=1
....:
zhang
qing
123
345

7、注意:
In [6]: list1=["zhang","qing",'123',345]
In [7]: i=0
In [8]: while i<=len(list1):
...: print(list1[i])
...: i+=1
...: zhang
qing
123
345
---------------------------------------------------------------------------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
