#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/8/21 9:22
# @Author : limingyu
# @Site :
# @File : Test_Base.py
# @Software: PyCharm
#python基础学习
import copy
##################List(列表):有序,有索引################
#1、list类似数组
name = ["li","wang","zhao",22,44]
#取单个值
print(name[3]) #用下标取某个值
print(name[-1]) #取最后一个值,从后往前数是-1,-2,-3...
#取多个值,左闭右开
print(name[0:2]) #['li', 'wang']
#从后往前数取多个值,不包含最后一个
print(name[-3:-1]) #['wang', 'zhao']
#从后往前数取多个值,包含最后一个
print(name[-3:]) #['zhao', 22, 44]
#取所有值
print(name[:]) #['li', 'wang', 'zhao', 22, 44]
#链式取值
print(name[0:3]) #['li', 'wang', 'zhao']
print(name[0:3][1:3]) #['wang', 'zhao']
print(name[0:3][1:2][0]) #['wang']
#2、修改,插入
name[1] = "sun"
print(name) #['li', 'sun', 'zhao', 22, 44]
#正向插入值
name.insert(2,'liu')
print(name) #['li', 'sun', 'liu', 'zhao', 22, 44]
#倒着插入,插入指定位置前面
name.insert(-1,'meng')
print(name) #['li', 'sun', 'liu', 'zhao', 22, 'meng', 44]
#最后位置追加
name.append(56)
print(name) #['li', 'sun', 'liu', 'zhao', 22, 'meng', 44, 56]
#移除某值
name.remove("sun")
print(name) #['li', 'liu', 'zhao', 22, 'meng', 44, 56]
#取出奇数位置的值,最后一个是步长,默认为1,
# name[0::2]等同name[::2]
print(name[0::2]) #['li', 'zhao', 'meng', 56]
del name #删除列表
#print(name) #NameError: name 'name' is not defined
#3、判断列表中是否存在一个元素
name_new = ["as","dd",3,4,5,6,7,23,43,"ui","re",54,6,32]
print(6 in name_new) #True
#统计某个元素个数
print("num_of_ele:",name_new.count(6))
#4、修改列表中所有的6为66666
for i in range(name_new.count(6)):
pos_of_ele = name_new.index(6)
name_new[pos_of_ele] = 66666
print(name_new) #['as', 'dd', 3, 4, 5, 66666, 7, 23, 43, 'ui', 're', 54, 66666, 32]
#5、列表追加到另一列表
name2 = ['wangwu','lisi',6]
name_new.extend(name2)
print(name_new) #['as', 'dd', 3, 4, 5, 66666, 7, 23, 43, 'ui', 're', 54, 66666, 32, 'wangwu', 'lisi', 6]
#6、copy:只复制第一层,内部的是地址,指向同一块地址
name3 = ['alex','jack','rain',[4,3,5,2],'li','liu',54,43]
name_shallowcopy = name3.copy() #浅拷贝
name_deepcopy = copy.deepcopy(name3)#深拷贝,完全拷贝,完全独立
name3[0] = 'ALEX'
name3[3][1] = 6666666666
name_shallowcopy[3][2] = 888888888
print(name3) #['ALEX', 'jack', 'rain', [4, 6666666666, 888888888, 2], 'li', 'liu', 54, 43]
print(name_shallowcopy) #['alex', 'jack', 'rain', [4, 6666666666, 888888888, 2], 'li', 'liu', 54, 43]
print(name_deepcopy) #['alex', 'jack', 'rain', [4, 3, 5, 2], 'li', 'liu', 54, 43]
#7、for循环取list中的值
product_list = [ #list中嵌套tuple
('Iphone',5800),
('Mac Air',8000),
('Mac Pro',9000)
]
for product_item in product_list: #不常用
p_name,p_price = product_item
print(p_name,p_price) #Iphone 5800 Mac Air 8000 Mac Pro 9000
for p_name,p_price in product_list: #推荐
print(p_name, p_price) # Iphone 5800 Mac Air 8000 Mac Pro 9000
#enumerate():输出带下标的元组
#枚举的元组,一个下标,一个内容
for item in enumerate(product_list):
print(item)
#(0, ('Iphone', 5800)) (1, ('Mac Air', 8000)) (2, ('Mac Pro', 9000))
for item in enumerate(product_list):
print(item[0],item[1][0],item[1][1])
#0 Iphone 5800 1 Mac Air 8000 2 Mac Pro 9000
for p_name,p_price in enumerate(product_list):
print(p_name,".", p_price)
#0 .('Iphone', 5800)1 .('Mac Air', 8000) 2 .('Mac Pro', 9000)
for p_name,p_price in enumerate(product_list):
print(p_name,".", p_price[0],p_price[1])
#0 . Iphone 5800 1 . Mac Air 8000 2 . Mac Pro 9000
############################### tuple(元组) ##########################
#tuple:元组,是只读列表,不允许修改
#只有连个方法index()和count()
tup = (1,2,"li")
#tup[1] = 4 #TypeError: 'tuple' object does not support item assignment
############################ 字符串(string) ########################
#1、移除空白,2、分割,3、长度,4,、索引,5、切片
#1、移除空白:strip()
username = input("username:")
if username.strip() == 'lihe': #客户输入lihe时可能多输入了空格,gu
print("welcome")
#2、数据拆分和组合
names = 'lihe,wang,liu'
name2 = names.split(",") #按逗号拆分成列表
print(name2) #['lihe', 'wang', 'liu']
print("|".join(name2)) #数据组合起来
# print("|".join(name2))
name = "li he"
print("" in name) #判断是否包含空格 True
#3.1、字符占位符
msg = "Hello,{name},your age is {age}"
msg2 = msg.format(name='lihe',age=28)
print(msg2) #Hello,lihe,your age is 28
#3.2、位置占位符
msg = 'haha:{0},hello:{1}'
msg2 = msg.format('lihe',29)
print(msg2) #haha:lihe,hello:29
#4、填充,总长40,不满时两边填充指定内容
name = "li he"
print(name.center(40,'-'))
#-----------------li he------------------
print(name.find('h')) #找到返回索引 3
print(name.find('j')) #未找到返回-1
#5、判断是否是数字,isdigit()
age = input("your age:")
if age.isdigit():
age = int(age)
print("your age is:",age)
else:
print("invalid data type")
#alphanumeric包括文字与数字的,isalnum()判断是否含特殊字符;
name = 'dfji33dfk'
print(name.isalnum()) #True
name = 'dfji!dfk'
print(name.isalnum()) #False
#以什么结尾,以什么开头
print(name.endswith('fk')) #True
print(name.startswith('df')) #True
#not的用法
a = [1,2,3,4]
if 5 not in a:
print("go")
#is:判断两个标识符是否引用同一个对象
#is not:判断两个标识符是否引用不同的对象
a = [1,2,3]
print(type(a) is list) #True
b = 'tr'
print(type(b) is str) #True
##################dic(字典):无序,无索引###################
#需求:存储14亿人信息,并将liming 改为wangming
#使用列表list,列表嵌套列表,还可以嵌套tuple
name = [1,[37048119562555,'liming','ShangHai'],'liyu',3,4,]
position = name.index('liyu') #查找liyu的位置
name[position] = 444444
print(name) #[1, [37048119562555, 'liming', 'ShangHai'], 444444, 3, 4]
#查找位置时,只能查找第一层list的索引,list中的list报错
#position = name.index(37048119562555) #ValueError: 37048119562555 is not in list
#1、字典中嵌套字典(字典也可嵌套list),key唯一
id_db = {
37048119562555:{
'name':"lihe",
'age' : 22,
'addr': 'ShanDong'
},
22048119562435: {
'name': "liming",
'age': 22,
'addr': 'ShangHai'
},
37042119237655: {
'name': "wangwu",
'age': 22,
'addr': 'BeiJing'
}
}
#2、修改字典中内容
#查看:通过key取值
print(id_db[37048119562555]) #{'name': 'lihe', 'age': 22, 'addr': 'ShanDong'}
#修改
id_db[37048119562555]['name'] = 'limingyu'
print(id_db[37048119562555]) #{'name': 'limingyu', 'age': 22, 'addr': 'ShanDong'}
#添加
id_db[37048119562555]['QQ'] = '919996385'
print(id_db[37048119562555]) #{'name': 'limingyu', 'age': 22, 'addr': 'ShanDong', 'QQ': '919996385'}
#删除1
del id_db[37048119562555]['addr']
print(id_db[37048119562555]) #{'name': 'limingyu', 'age': 22, 'QQ': '919996385'}
#删除2
id_db[37048119562555].pop('QQ')
print(id_db[37048119562555]) #{'name': 'limingyu', 'age': 22}
#3、获取内容
value = id_db.get(111111111)
print(value) #None
#value = id_db[111111111]
#print(value) #KeyError: 111111111
#4、更新内容,有则替换,无则添加
dic2 = {
"name":'zhangsan',
37048119562555:{
'name':"xiaoran",
}
}
id_db.update(dic2)
print(id_db)
#{37048119562555: {'name': 'xiaoran'}, 22048119562435: {'name': 'liming', 'age': 22, 'addr': 'ShangHai'},
# 37042119237655: {'name': 'wangwu', 'age': 22, 'addr': 'BeiJing'}, 'name': 'zhangsan'}
#5、字典转化为列表,元素超过50万条,不进行转换
print(id_db)
#{37048119562555: {'name': 'xiaoran'}, 22048119562435: {'name': 'liming', 'age': 22, 'addr': 'ShangHai'},
#37042119237655: {'name': 'wangwu', 'age': 22, 'addr': 'BeiJing'}, 'name': 'zhangsan'}
print(id_db.items())
#dict_items([(37048119562555, {'name': 'xiaoran'}), (22048119562435, {'name': 'liming', 'age': 22, 'addr': 'ShangHai'}),
# (37042119237655, {'name': 'wangwu', 'age': 22, 'addr': 'BeiJing'}), ('name', 'zhangsan')])
#6、判断字典是否包含某个key
print(id_db.keys()) #所有的keys
print(id_db.values()) #所有的values
#id_db.hash_key(37048119562555) #only 2.0
37048119562555 in id_db #equal to hash_key()
#7、取一个key,如果不存在,就设置key/value
id_db.setdefault(110,'helloworld')
print(id_db)
#{37048119562555: {'name': 'xiaoran'}, 22048119562435: {'name': 'liming', 'age': 22, 'addr': 'ShangHai'},
# 37042119237655: {'name': 'wangwu', 'age': 22, 'addr': 'BeiJing'},'name': 'zhangsan', 110: 'helloworld'}
#取每一个key设置为同一个value(dd)
print(id_db.fromkeys([1,2,3,4],'dd')) #{1: 'dd', 2: 'dd', 3: 'dd', 4: 'dd'}
print(id_db) #formkeys()方法不改变原来的字典
#{37048119562555: {'name': 'xiaoran'}, 22048119562435: {'name': 'liming', 'age': 22, 'addr': 'ShangHai'},
# 37042119237655: {'name': 'wangwu', 'age': 22, 'addr': 'BeiJing'}, 'name': 'zhangsan', 110: 'helloworld'}
#8、for循环取字典中的值
for k,v in id_db.items():#效率低,因为有一个dict to list过程,数据量大时不建议使用
print(k,v)
#37048119562555 {'name': 'xiaoran'}
#22048119562435 {'name': 'liming', 'age': 22, 'addr': 'ShangHai'}
#37042119237655 {'name': 'wangwu', 'age': 22, 'addr': 'BeiJing'}
#name zhangsan
#110 helloworld
print(k)
print(v)
#37048119562555
#{'name': 'xiaoran'}
#22048119562435
#{'name': 'liming', 'age': 22, 'addr': 'ShangHai'}
#37042119237655
#{'name': 'wangwu', 'age': 22, 'addr': 'BeiJing'}
#name
#zhangsan
#110
#helloworld
#建议如下写法,效率高
for key in id_db:
print(key,id_db[key])
#37048119562555 {'name': 'xiaoran'}22048119562435 {'name': 'liming', 'age': 22, 'addr': 'ShangHai'}
#37042119237655 {'name': 'wangwu', 'age': 22, 'addr': 'BeiJing'}name zhangsan110 helloworld
python基础之list,tuple,dict,string
最新推荐文章于 2023-02-17 19:48:44 发布