今日内容
* 元祖及内置方法
* 字典及内置方法
* 集合及内置方法
* 字符编码
元祖tuple
与列表类似可以存多个值,但是不同的是元祖本身不能被修改
```python
一:基本使用:tuple
1 用途:记录多个值,当多个值没有改的需求,此时用元组更合适
2 定义方式:在()内用逗号分隔开多个任意类型的值
t=(1,1.3,'xx',('a','b'),[1,2]) t=tuple((1,1.3,'xx',('a','b'),[1,2]))
print(t,type(t))
t1=tuple('hello')
print(t1)
3 常用操作+内置的方法
优先掌握的操作:
1、按索引取值(正向取+反向取):只能取
t=('egon',123,['a','b'])
print(id(t[0]))1
print(id(t[1]))
print(id(t[2]))
t[2][0]='A'
print('='*50)
print(id(t[0]))
print(id(t[1]))
print(id(t[2]))
t[0]='EGON'
t[2]='xxxx'
t[2][0]='A'
print(t)
2、切片(顾头不顾尾,步长)
t=(1,2,3,4,5)
print(t[0:3])
print(t)
3、长度
4、成员运算in和not in
5、循环
for item in ('a','b','c'):
print(item)
需要掌握的操作
t=('a','b','c','a')
print(t.count('a'))
print(t.index('a',1,10))
print(t.index('xxx',1,10))
二:该类型总结
1 存多个值
2 有序
3 不可变
```
字典dict
```python
6b 不可变类型=》可hash类型
可变类型 =》不可以hash类型
一:基本使用dict
1 用途:记录多个值,每一个值都对应的key用来描述value的作用
2 定义方式:在{}内用逗号分隔开多 个key:value,其中value可以是任意类型,而key必须是不可变的类型,通常情况下应该str类型
dic={0:'aaa',1:'bbb',2:'cccc'} dic=dict({0:'aaa',1:'bbb',2:'cccc'})
print(dic,type(dic))
print(dic[0])
dic={[1,2]:'aaa'}
dic={(1,2):'aaa'}
print(dic[(1,2)])
用法一:
dic=dict(x=1,y=2,z=3)
print(dic)
用法二:
userinfo=[
['name','egon'],
['age',18],
['sex','male']
]
d={}
for k,v in userinfo: k,v=['name', 'egon']
print(k,v)
d[k]=v
print(d)
d=dict(userinfo)
print(d)
3 常用操作+内置的方法
优先掌握的操作:
1、按key存取值:可存可取
dic={'name':'egon'}
print(dic['name'])
dic['name']='EGON'
print(dic)
dic['age']=18
print(dic)
2、长度len
dic={'name':'egon','age':18,'name':'EGON','name':'XXXX'}
print(dic)
print(len(dic))
3、成员运算in和not in:字典的成员运算判断的是key
dic={'name':'egon','age':18,}
print(18 in dic)
print('age' in dic)
4、删除
dic={'name':'egon','age':18,}
通用
del dic['name']
print(dic)
del dic['xxx'] key不存在则报错
res=dic.pop('age') 删除key对应的value,并返回value
print(dic)
print(res)
dic.pop('xxx') key不存在则报错
res=dic.popitem()
print(dic)
print(res)
5、键keys(),值values(),键值对items() 注意python2与python3之间的区别
dic={'name':'egon','age':18,}
print(dic.keys())
l=[]
for k in dic.keys():
l.append(k)
print(l)
print(list(dic.keys()))
print(dic.values())
print(list(dic.values()))
print(dic.items())
print(list(dic.items()))
6、循环
dic={'name':'egon','age':18,'sex':'male'}
for k in dic.keys():
print(k,dic[k])
for k in dic:
print(k,dic[k])
for v in dic.values():
print(v)
for k,v in dic.items():
print(k,v)
8 dic.get()
dic={'name':'egon','age':18,'sex':'male'}
dic['xxx']
v=dic.get('name')
print(v)
v=dic.get('xxx')
print(v)
需要掌握的操作
dic.fromkeys()的用法:
l=['name','age','sex']
dic={'name':None,'age':None,'sex':None}
dic={}
for k in l:
dic[k]=None
print(dic)
dic=dic.fromkeys(l,None)
print(dic)
old_dic={'name':'egon','age':18,'sex':'male'}
new_dic={'name':'EGON','x':1,'y':2}
old_dic.update(new_dic)
print(old_dic)
setdefault:有则不动/返回原值,无则添加/返回新值
dic={'name':'egon','age':18}
res=dic.setdefault('name','EGON') 字典中已经存在key则不修改,返回已经存在的key对应的value
print(dic)
print(res)
res=dic.setdefault('sex','male') 字典不存在key则添加"sex":"male",返回新的value
print(dic)
print(res)
二:该类型总结
1 存多个值
2 无序
3 可变
dic={'x':1}
print(id(dic))
dic['x']=2
print(id(dic))
练习1:
nums=[11,22,33,44,55,66,77,88,99,90]
dic={
'k1':[],
'k2':[]
}
for num in nums:
if num > 66:
dic['k1'].append(num)
else:
dic['k2'].append(num)
print(dic)
练习2:
s='hello alex alex say hello sb sb'
words=s.split()
dic={}
print(words)
for word in words:
if word in dic:
dic[word]+=1
else:
dic[word]=1
print(dic)
s='hello alex alex say hello sb sb'
words=s.split()
dic={}
for word in words: word="hello"
dic.setdefault(word,words.count(word)) {'hello':2,"alex":2,"say":1,}
print(dic)
```
集合set
```python
pythons=['李二丫','张金蛋','李银弹','赵铜蛋','张锡蛋','alex','oldboy']
linuxs=['lxx','egon','张金蛋','张锡蛋','alex','陈独秀']
l=[]
for stu in pythons:
if stu in linuxs:
l.append(stu)
print(l)
一:基本使用:set
1 用途: 关系运算,去重
2 定义方式: 在{}内用逗号分开个的多个值
集合的三大特性:
2.1 每一个值都必须是不可变类型
2.2 元素不能重复
2.3 集合内元素无序
s={1,3.1,'aa',(1,23),} s=set({1,3.1,'aa',(1,23),})
print(s,type(s))
s={1,1,1,1,1,1,1,1,1,2,3}
print(s)
s={'a','b','c'}
s[0]
s=set('hello')
print(s)
print(set(['a','b','c',[1,2]]))
3 常用操作+内置的方法
pythons={'李二丫','张金蛋','李银弹','赵铜蛋','张锡蛋','alex','oldboy'}
linuxs={'lxx','egon','张金蛋','张锡蛋','alex','陈独秀'}
取及报名python课程又报名linux课程的学员:交集
print(pythons & linuxs)
print(pythons.intersection(linuxs))
取所有报名老男孩课程的学员:并集
print(pythons | linuxs)
print(pythons.union(linuxs))
取只报名python课程的学员: 差集
print(pythons - linuxs)
print(pythons.difference(linuxs))
取只报名linux课程的学员: 差集
print(linuxs - pythons)
print(linuxs.difference(pythons))
取没有同时报名两门课程的学员:对称差集
print(pythons ^ linuxs)
print(pythons.symmetric_difference(linuxs))
是否相等
s1={1,2,3}
s2={3,1,2}
print(s1 == s2)
父集:一个集合是包含另外一个集合
s1={1,2,3}
s2={1,2}
print(s1 >= s2)
print(s1.issuperset(s2))
s1={1,2,3}
s2={1,2,4}
print(s1 >= s2)
子集
s1={1,2,3}
s2={1,2}
print(s2 <= s1)
print(s2.issubset(s1))
需要掌握操作
s1={1,2,3}
s1.update({3,4,5})
print(s1)
s1={1,2,3}
res=s1.pop()
print(res)
s1={1,2,3}
res=s1.remove(3) 单纯的删除,返回值为None
print(s1)
s1={1,2,3}
s1.add(4)
print(s1)
s1={1,2,3}
s2={1,2}
s1.difference_update(s2) s1=s1.difference(s2)
print(s1)
s1={1,2,3}
res=s1.discard(3) 单纯的删除,返回值为None
print(s1)
print(res)
s1.remove(444444) 删除的元素不存在则报错
s1.discard(444444) 删除的元素不存在不会报错
s1={1,2,3}
s2={1,2,4}
print(s1.isdisjoint(s2)) 如果两个集合没有交集则返回True
s1={1,2,3}
s2={4,5,6}
print(s1.isdisjoint(s2)) 如果两个集合没有交集则返回True
二:该类型总结
1 存多个值
2 无序
3 set可变
s={1,2,3}
print(id(s))
s.add(4)
print(id(s))
集合去重
局限性
1、无法保证原数据类型的顺序
2、当某一个数据中包含的多个值全部为不可变的类型时才能用集合去重
names=['alex','egon','alex','alex','egon','lxx']
s=set(names)
print(s)
l=list(s)
print(l)
stus_info=[
{'name':'egon','age':18},
{'name':'alex','age':73},
{'name':'oldboy','age':84},
{'name': 'egon', 'age': 18},
{'name': 'egon', 'age': 18},
{'name': 'egon', 'age': 18},
{'name': 'oldboy', 'age': 84},
]
set(stus_info) 报错
l=[]
for info in stus_info:
if info not in l:
l.append(info)
print(l)
stus_info=l
print(stus_info)
```
username=input().strip(?
if username == 'jason':
print('goood job')
print(username)
print(username.rstrip('df'))
a=username.split('a',4)
print(a)
leetcode 初探 两数之和 多种解法:
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode``
:rtype: ListNode
"""
cur_1 = l1
cur_2 = l2
int_num1 = 0
int_num2 = 0
count_1 = 0
count_2 = 0
int_sum_of_two_linklist = 0
while cur_1 is not None or cur_2 is not None:
if cur_1 is not None:
int_num1 = 10 ** count_1 * cur_1.val + int_num1
count_1 += 1
cur_1 = cur_1.next
if cur_2 is not None:
int_num2 = 10 ** count_2 * cur_2.val + int_num2
count_2 += 1
cur_2 = cur_2.next
int_sum_of_two_linklist = int_num1 + int_num2
print(int_sum_of_two_linklist)
游标指向链表l1的头
pre = l1
cur = l1
while int_sum_of_two_linklist != 0:
if pre is not None:
pre.val = int_sum_of_two_linklist % 10
print(cur.val)
cur = pre
pre = pre.next
else:
node = ListNode(int_sum_of_two_linklist % 10)
print(node.val)
print(node.next)
cur.next = node
cur = cur.next
int_sum_of_two_linklist = int_sum_of_two_linklist / 10
return l1
class Solution:
def addTwoNumbers(self, l1, l2):
n1=[]
n2=[]
lv1=l1.val
lv2=l2.val
n1.append(l1.val)
n2.append(l2.val)
while l1.next and l2.next:
n1.append(l1.val)
n2.append(l2.val)
l1=l1.next
l2=l2.next
else:
while l1.next !=None:
n1.append(l1.val)
l1=l1.next
while l2.next !=None:
n2.append(l2.val)
l2=l2.next
n1=n1[::-1]
n2=n2[::-1]
class Solution:
def addTwoNumbers(self, l1, l2):
n1 = []
n2 = []
nl = []
while l1.next and l2.next:
n1.append(l1.val)
n2.append(l2.val)
l1 = l1.next
l2 = l2.next
while l1.next != None:
n1.append(l1.val)
l1 = l1.next
while l2.next != None:
n2.append(l2.val)
l2 = l2.next
if l1.next==0 and l2.next==0:
n1.append(l1.val)
n2.append(l2.val)
n1 = n1[::-1]
n2 = n2[::-1]
res1 = 0
res2 = 0
number1 = len(n1)
number2 = len(n2)
for i in n1:
if number1 >= 0:
res1 += i * 10 ** (len(n1) - number1)
number1 += -1
for i in n2:
if number2 >= 0:
res2 += i * 10 ** (len(n2) - number2)
number2 += -1
print(res1)
print(res2)
res3 = list(str(res1 + res2))
res3 = res3[::-1]
for i in res3:
nl.append(int(i))
return
2.简单购物车,要求如下:
实现打印商品详细信息,用户输入商品名和购买个数,则将商品名,价格,购买个数加入购物列表,如果输入为空或其他非法输入则要求用户重新输入
msg_dic={
'apple':10,
'tesla':100000,
'mac':3000,
'lenovo':30000,
'chicken':10,
}
小提示:打印的时候即需要拿到字典的key也需要拿到对应的value
key_name = input('请输入要购买的商品名称')
key_name_number = input('请输入要购买的个数')
while (key_name not in msg_dic ) or key_name ==0 :
print('输入内容错误 ,请重新输入')
key_name=input('请输入要购买的商品名称')
key_name_number=input('请输入要购买的个数')
value=msg_dic[key_name]*key_name_number
print(key_name,key_name_number,'num value=%s'%value)
3.统计s='hello alex alex say hello sb sb'中每个单词的个数
s='hello alex alex say hello sb sb sb sbsbsbbs sb,sb , '
s=s.split()
结果如:{'hello': 2, 'alex': 2, 'say': 1, 'sb': 2}
d1 = {}
for i in s:
if i in d1:
d1[i] += 1
else:
d1[i] = 1
print(d1)
4.关系运算
有如下两个集合,pythons是报名python课程的学员名字集合,linuxs是报名linux课程的学员名字集合
pythons={'alex','egon','yuanhao','wupeiqi','gangdan','biubiu'}
linuxs={'wupeiqi','oldboy','gangdan'}
1. 求出即报名python又报名linux课程的学员名字集合
2. 求出所有报名的学生名字集合
3. 求出只报名python课程的学员名字
4. 求出没有同时这两门课程的学员名字集合
double=set(pythons and linuxs)
print(double)
all=set(pythons | linuxs)
print(all)
op=set(pythons-linuxs)
print(op)
no=set.difference(pythons,linuxs)
print(no)
5. 对列表
l=['a','b',1,'a','a'] x`内的元素完成去重得到新列表.
拔高:如果想去重并且想保持列表原来的顺序该如何做?
l1=[]
for i in l :
if i not in l1:
l1.append(i)
print(l1)
6.对如下列表中的元素去重(),得到新列表,且新列表一定要保持列表原来的顺序
l=[
{'name':'egon','age':18,'sex':'male'},
{'name':'alex','age':73,'sex':'male'},
{'name':'egon','age':20,'sex':'female'},
{'name':'egon','age':18,'sex':'male'},
{'name':'egon','age':18,'sex':'male'},
]
l1=[]
for i in l :
if i not in l1:
l1.append(i)
print(l1)