当前位置: 移动技术网 > IT编程>脚本编程>Python > Python的列表实例介绍

Python的列表实例介绍

2018年02月11日  | 移动技术网IT编程  | 我要评论

午夜忍者,ipone,婴儿翻白眼

列表:

In [59]: names = ['IBM','Blue Polo','hello','hello']
In [61]: names[1]           ##列表里的第1个
Out[61]: 'Blue Polo'

In [62]: names[0]           ##列表里的第0个
Out[62]: 'IBM'

In [63]: names.append('BAT')        ##append,在末尾添加一个

In [64]: names
Out[64]: ['IBM', 'Blue Polo', 'hello', 'hello', 'BAT']

In [65]: names.count('hello')       ##统计在该列表中hello出现的次数
Out[65]: 2

In [66]: name = ['Li Lei','Han Meimei']     ##定义一个新的列表

In [67]: names.extend(name)         ##extend,将两个列表合到一块

In [68]: names
Out[68]: ['IBM', 'Blue Polo', 'hello', 'hello', 'BAT', 'Li Lei', 'Han Meimei']

In [74]: names.index('Li Lei')      ##index检索列表中该元素第一次出现的位置
Out[74]: 5

In [76]: names.pop()        ##pop删除列表中最后一个元素
Out[76]: 'Han Meimei'

In [77]: names
Out[77]: ['IBM', 'Blue Polo', 'hello', 'hello', 'BAT', 'Li Lei']

In [79]: names.insert(3,'Han Meimei')   ##insert在3号位置添加Han Meimei

In [80]: names
Out[80]: ['IBM', 'Blue Polo', 'hello', 'Han Meimei', 'hello', 'BAT', 'Li Lei']

names.remove('IBM')   ##remove删除 列表里的第一个IBM。

names.reverse()         ##reverse将列表反转

names.sort()            ##sort排序(数字>大写字母>小写字母)

del name[5:10]      ##删除列表中的第5个元素到第10个元素

In [83]: for i in  range(names.count('hello')):
    ...:     names[names.index('hello')] = 'HP'
                        ##更改列表中的元素,将hello改为HP

字符串变为列表,列表变为字符串:

In [107]: a = ('asdfasdfqwerxcfdsa')    

In [108]: list(a)       ##将字符串a变为列表

'*'.join(list(a))       ##将列表又转换为a,引号里为分隔符

str(a)              ##变为字符串格式
In [146]: with open ('test2.txt','r') as f:         ##使用这种方式不用关闭。
     ...:     for i in f:
     ...:         print i
     ...:         

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网