网站首页 文章专栏 Python基础篇---列表与元组操作

Python基础篇---列表与元组操作

编辑时间:2018-05-10 15:45:15 作者:苹果 浏览量:2521




#列表操作 类似于字符串及PHP的数组操作
test_list=['123','abc','ABC'];
print (test_list[0]) #123
print (test_list[1:])#['abc', 'ABC']
print (test_list*2)  # 输出两次['123', 'abc', 'ABC', '123', 'abc', 'ABC']
print (test_list+['z']) #列表只能连接列表 生成新列表['123', 'abc', 'ABC', 'z'] list未发生变
test_list[2]='xyz' # 元素重新赋值['123', 'abc', 'xyz']


del test_list[0] # 删除,改变数组['abc', 'xyz']
print (test_list)
length=len (test_list )
print (length) #列表长度 2


print (2 in test_list) #false 判读是否存在列表


for x in test_list : print(x,end=';') #遍历列表数据以;隔开abc;xyz;


print (max(test_list)) #列表最大值
print(min(test_list))#列表最小值


test_list.append('0') #列表末尾追加 ['abc', 'xyz', '0']
print(test_list.count('0')) #元素出现的次数 1

test_list.extend('z') #list添加元素或列表,list发生改变['abc', 'xyz', '0', 'z']


print (test_list.index('z')) #查找元素第一次出现位置  # 3
test_list.insert(1,'insert') #插入 ['abc', 'insert', 'xyz', '0', 'z']


test_list.pop() #移除最后一个元素['abc', 'insert', 'xyz', '0']
test_list.pop(1) #移除第二个元素['abc', 'xyz', '0']

test_list.remove('0') #移除匹配到的第一个元素['abc', 'xyz']


test_list.reverse() #反转列表['xyz', 'abc']


test_list.sort() #排序['abc', 'xyz']


new_list=test_list.copy()#复制列表


test_list.clear()#清空列表[]


print ('\n')#换行
#元组操作 元组与列表类似,元组用"()"标识。内部元素用逗号隔开。但是元组不能二次赋值,相当于只读列表
test_tuple=('123','abc','ABC')
print (test_tuple[0]) #123
print(test_tuple[1:])#('abc', 'ABC')
print (test_tuple*2)# ('123', 'abc', 'ABC', '123', 'abc', 'ABC')
new_tuple=test_tuple+('a',1) #元组的扩展只能通过建立新元组来进行 ('123', 'abc', 'ABC', 'a', 1)
print(new_tuple)

#元组没有append(),insert(),pop()这样的方法。其他获取元素的方法和list是一样的,你可以正常地使用test_tuple[0],test_tuple[-1],但不能赋值成另外的元素

#不可变的tuple有什么意义?因为tuple不可变,所以代码更安全。如果可能,能用tuple代替list就尽量用tuple


del new_tuple  #因元组的不可操作性,只能删除整个元组

eg:
#print(new_tuple) #报错NameError: name 'raw_input' is not defined


new_tuple_list=list(test_tuple) #['123', 'abc', 'ABC'] 元组转列表

str='abcdefg';
temp_list=list(str) #['a', 'b', 'c', 'd', 'e', 'f', 'g'] 字符串转列表
print(temp_list)
#####PS:注意最好别用特殊字符,函数名做变量名

new_list_tuple=tuple(temp_list) #列表转元组 ('a', 'b', 'c', 'd', 'e', 'f', 'g')
print(new_list_tuple)


    出自:何冰华个人网站

    地址:https://www.hebinghua.com/

    转载请注明出处


来说两句吧
最新评论