网站首页 美食营养 游戏数码 手工爱好 生活家居 健康养生 运动户外 职场理财 情感交际 母婴教育 时尚美容 知识问答

python之列表(List)介绍与循环遍历

时间:2024-10-13 22:01:16

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使用中括号,且用逗号把不同的数据分开即可。

python之列表(List)介绍与循环遍历

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

python之列表(List)介绍与循环遍历

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

python之列表(List)介绍与循环遍历

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

python之列表(List)介绍与循环遍历
© 2025 五度知识库
信息来自网络 所有数据仅供参考
有疑问请联系站长 site.kefu@gmail.com