1. 列表 pop()方法
pop() 函数用于移除列表中的一个元素(默认最后一个元素),并且返回该元素的值。
list1 = ['Google', 'Runoob', 'Taobao']
list_pop=list1.pop(1)
print "删除的项为 :", list_pop
print "列表现在为 : ", list1
以上实例输出结果如下:
删除的项为 : Runoob
列表现在为 : ['Google', 'Taobao']
2. replace()方法
Python replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。
- old – 将被替换的子字符串。
- new – 新字符串,用于替换old子字符串。
- max – 可选字符串, 替换不超过 max 次
以下实例展示了replace()函数的使用方法:
#!/usr/bin/python
str = "this is string example....wow!!! this is really string";
print str.replace("is", "was");
print str.replace("is", "was", 3);
以上实例输出结果如下:
thwas was string example....wow!!! thwas was really string
thwas was string example....wow!!! thwas is really string
3. 查找列表中某个值得位置
p=list.index(value)
- list 为列表的名字
- value为查找的值
- p为value在list的位置
4. 翻转列表
定义一个列表,并将它翻转。
例如,对调第一个和第三个元素:
翻转前 : list = [10, 11, 12, 13, 14, 15]
翻转后 : [15, 14, 13, 12, 11, 10]
code1:
def Reverse(lst):
return [ele for ele in reversed(lst)]
lst = [10, 11, 12, 13, 14, 15]
print(Reverse(lst))
以上实例输出结果为:
[15, 14, 13, 12, 11, 10]
code2:
def Reverse(lst):
lst.reverse()
return lst
lst = [10, 11, 12, 13, 14, 15]
print(Reverse(lst))
以上实例输出结果为:
[15, 14, 13, 12, 11, 10]
code3:
def Reverse(lst):
new_lst = lst[::-1]
return new_lst
lst = [10, 11, 12, 13, 14, 15]
print(Reverse(lst))
以上实例输出结果为:
[15, 14, 13, 12, 11, 10]