码迷,mamicode.com
首页 > 编程语言 > 详细

Python基础(二)

时间:2018-10-12 21:05:56      阅读:220      评论:0      收藏:0      [点我收藏+]

标签:字符串   append   local   ica   format   height   查找   返回   方便   

1、列表list
#1.创建
lst = [6, 4, 8, 10 ,2, True, 11.0]
#2.获取和设置元素的值
print(lst[6]) #获取
lst[6] = 11
print(lst[6]) #设置
lst
print(type(lst)) #list
#3.运算符
print(lst+[‘a‘,‘b‘,‘c‘]) #[6, 4, 8, 10, 2, True, 11, ‘a‘, ‘b‘, ‘c‘]
print(lst*2) #[6, 4, 8, 10, 2, True, 11, 6, 4, 8, 10, 2, True, 11]
print(lst[2]) #8
print(lst[1:5]) # 4, 8, 10, 2
print(lst[1:5:2]) # 4,10
print(lst[-1:-5:-2]) #[11, 2]
print(lst[:4]) #6, 4, 8, 10
#4.方法
#1) 查找 index、count、sort、sorted、reverse、reversed
lst = [6, 4, 8, 10 ,2, 4]
print(lst.index(4)) # 1 ,通过元素查找位置
print(lst.index(4, lst.index(4)+1)) #5
print(lst.count(4)) # 2
lst.sort() #lst本身
print(lst) #[2, 4, 4, 6, 8, 10]
lst = [6, 4, 8, 10 ,2, 4]
lst.sort(reverse=True)
print(lst) #[10, 8, 6, 4, 4, 2]
lst.reverse() #反转
print(lst) #[2, 4, 4, 6, 8, 10]
#还有一种排序方法,不是上面的方法sort,而是函数 sorted
lst = [3,5,1,7]
lst2 = sorted(lst) #默认从小到大
print(lst2)
lst = [3,5,1,7]
lst2 = sorted(lst, reverse=True) #从大到小
print(lst2)
# 2) 增加 insert、append、extend
lst = [1, 3, 5, 7, 9]
#在第2个位置,插入4
lst.insert(2, 4)
print(lst) #[1, 3, 4, 5, 7, 9]
#在末尾插入一个元素
lst.append(10) # [1, 3, 4, 5, 7, 9, 10]
print(lst)
#lst.extend
lst.extend([11,12,13]) #[1, 3, 4, 5, 7, 9, 10, 11, 12, 13]
print(lst)
#区别
append():不能添加多个元素
extend():能添加多个元素,但参数必须是列表
insert()
lst.append([14,15,16]) #[1, 3, 4, 5, 7, 9, 10, 11, 12, 13,[14,15,16]]
print(lst)
注:append()、extend()、insert()都不属于BIF,所以使用时都必须指出相应的表
# 3)删除 pop、remove、del、clear
remove():知道要删除的元素就行
del 是一个语句 del+表名
pop():弹出最后一个元素,且可根据索引值弹出元素
clear()删除全部,但是保留空表
lst = [1,2,3, 5, 7, 9]
#删除1个:按照索引
lst.pop(1)
print(lst) #[1, 3, 5, 7, 9]
lst.pop() #不写参数,删除最后一个
print(lst) #[1, 3, 5, 7]
#删除1个:按照内容
lst.remove(5)
print(lst) #[1, 3, 7]
#删除全部
lst.clear()
print(lst) #[]
#删除列表
del lst
#print(lst)
#拷贝
lst = [1,2, 3, 5, 7, 9]
lst2 = lst.copy()
print(lst2)
题目:
1、 lst = []
for i in range(5):
lst.append(i*2)
lst
#[0, 2, 4, 6, 8]
列表表达式
[ i*2 for i in range(5)]
#[0, 2, 4, 6, 8]
2、[[i,i+1] for i in range(5)]
#[[0, 1], [1, 2], [2, 3], [3, 4], [4, 5]]
3、[i.upper() for i in ‘hello‘]
#[‘H‘, ‘E‘, ‘L‘, ‘L‘, ‘O‘]
4、[len(i) for i in ‘I Hate You‘.split()]
#[1, 4, 3]
[len(i) for i in [‘I‘,‘Hate‘,‘You‘]]
#[1, 4, 3]
5、 lst = []
for i in range(5):
if i*2 <= 4:
lst.append(i*2)
lst
#[0, 2, 4]
[i*2 for i in range(5) if i*2<=4]
#[0, 2, 4]
6、[(i,i+1,i+2,i+3) for i in range(5)]
#[(0, 1, 2, 3), (1, 2, 3, 4), (2, 3, 4, 5), (3, 4, 5, 6), (4, 5, 6, 7)]
7、lst = []
for i in [1,2,3]:
for j in [3,1,4]:
if i != j:
lst.append((i,j))
lst
#[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
[(i,j) for i in [1,2,3] for j in [3,1,4] if i != j]
#[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
8、vec = [[1,2,3], [4,5,6], [7,8,9]]
[num for elem in vec for num in elem]
#[1, 2, 3, 4, 5, 6, 7, 8, 9]
lst = []
for elem in vec:
for num in elem:
lst.append(num)
lst
#[1, 2, 3, 4, 5, 6, 7, 8, 9]
2、元组tuple
# 1.创建
t1 = (1, 1.0, True)
t2 = 1, 1.0, True #小括号可以省略
t3 = (1,) #如果只有1个数,后面需要加入逗号
t4 = 1,
t5 = (1) #这个不是元组,它是整数,也就1
print(type(t1)) #tuple
print(type(t2))
print(type(t3))
print(type(t4))
print(type(t5)) #int
t = 12345, 54321, ‘hello!‘
print(t[0]) #12345
print(t) # (12345, 54321, ‘hello!‘)
u = t, (1, 2, 3, 4, 5)
print(u) #((12345, 54321, ‘hello!‘), (1, 2, 3, 4, 5))
#元组的赋值:比较灵活
a,b,c=1,2,3
print(a, b, c)
a,b,c=‘123‘
print(a, b, c)
(a,b,c)=(1,2,3)
print(a, b, c)
a=1,2,3
print(a) #(1,2,3)
#元组和列表的相互转换,用list函数和tuple函数
list((1, 2, 3)) # 元组变列表
tuple([1, 2, 3]) #列表变元组
#列表和字符串的相互转换
list(‘abc‘) #字符串变列表 [‘a‘, ‘b‘, ‘c‘]
‘‘.join([‘a‘, ‘b‘, ‘c‘])#列表变字符串 ‘abc‘
3、集合(无序、不重复)
set1 = {4, 6, 11, 3, 1, 3}
for i in set1:
print(i)
print(type(set1)) #set
#list转成set,用set函数 :可以把list的重复元素去掉
set2 = set([1, 3, 3, 3, 5, 7]) #list转成set类型
print(set2)
#str转set,也是用上面set方法
#创建空集合
set1 = {} #这么写是错的,原因是字典占用了。
set1 = set() #这些是对的
注:1、集合是无序的,所以不能像序列一样访问,可以通过迭代的方法读出来;
2、in or not in 判断元素是否存在
3、add()、remove()增加和删除已知元素
4、frozenset()将集合里的元素冰冻
4、字典
#1. 创建
(1)fromkeys()创建并返回一个新的字典
(2)keys()、values()、items()
(3)get(键)访问字典
(4)copy()复制字典,值相同,位置不同
(5)pop()弹出字典的值,popitem()弹出字典的项
(6)update(键+值)更新字典
#方法1:最常用
dic1 = {‘cn‘:‘china‘, ‘us‘:‘America‘, ‘age‘:18}
print(dic1)
print(type(dic1)) #dict
#方法2:key值不能加引号
dic2 = dict(cn=‘china‘, us=‘America‘)
print(dic2)
#方法3:实际是把列表中的元组元素,转成字典
dic3 = dict([(‘cn‘,‘china‘),(‘us‘,‘America‘)])
print(dic3)
#创建空字典
dic4 = {}
print(type(dic4))
#获取和设置元素
dic = {‘cn‘:‘china‘, ‘us‘:‘America‘}
print(dic[‘cn‘]) #获取值:通过key获取value
dic[‘cn‘] = ‘CHINA‘ #设置值
print(dic[‘cn‘])
#如果key不存在,会出错
#print(dic[‘xxx‘])
#如果key不存在,不想报错,可以用get方法,同时get还可以可以设置默认值
print(dic.get(‘xxx‘)) #返回None
print(dic.get(‘xxx‘, ‘yyyy‘)) #xxx不存在,返回yyyy
#2)运算符
dic = {‘cn‘:‘china‘, ‘us‘:‘America‘}
print(‘cn‘ in dic) #True
print(‘jp‘ not in dic) #True
#3)方法
#增
dic = {‘cn‘:‘china‘, ‘us‘:‘America‘}
dic[‘fr‘] = ‘french‘ #增加
print(dic)
dic.update({‘a‘:‘1‘,‘b‘:‘2‘})
print(dic)
#删
dic = {‘cn‘:‘china‘, ‘us‘:‘America‘}
dic.pop(‘us‘) #通过key删除一行
print(dic)
dic.clear() #清空
print(dic) #{}
#改
dic = {‘cn‘:‘china‘, ‘us‘:‘America‘}
dic[‘cn‘] = ‘CHINA‘
print(dic)
#查
dic = {‘cn‘:‘china‘, ‘us‘:‘America‘}
#1)通过key查vlaue
print(dic[‘cn‘]) #方便,但是如果没有查到,会报错
print(dic.get(‘cn‘)) #没有查到,返回None,还可以设置默认值
#2)查询所有的key
print(dic.keys())
for key in dic.keys():
print(key,dic[key])
#3)查询所有的value
print(dic.values())
#4)查询所有的item
print(dic.items())
for item in dic.items():
print(item[0],item[1])
for (k,v) in dic.items():
print(k,v)
#拷贝
dic = {‘cn‘:‘china‘, ‘us‘:‘America‘}
dic2 = dic.copy()
print(dic2)
dic = {‘cn‘:‘china‘, ‘us‘:‘America‘}
for x in dic: #如果直接写字典的名称,取得值是key
print(x)
list(zip([1,3,5],[‘a‘, ‘b‘, ‘c‘]))
5、函数
def foo1():
return 1;
print(foo1())
def foo2():
print(1)
foo2()
#分别求1到100, 1到200的和
def foo(n):
sum = 0
for i in range(n+1):
sum += i
return sum
print(foo(100))
result = foo(200)
print(result)
#修改水仙花数
def foo():
for number in range(100, 1000):
a = number % 10 #个位数
b = number //10 % 10 #十位数,或number%100//10
c = number // 100 #百位数
if is_narcissistic(number, a, b, c):
print(number)
def is_narcissistic (digit, x, y, z):
if digit == x**3 + y**3 + z**3:
return True
else:
return False
foo()
#改写求闰年
def is_leap_year(y):
if (y % 4 == 0 and y % 100 != 0) or (y % 400 == 0):
return True
else:
return False
def foo():
year = 3000
if is_leap_year(year):
print(‘%d是闰年‘%year)
else:
print(‘{}不是闰年‘.format(year))
foo()
def sum(a, b, c):
return a + b + c
sum(1, 2, 3) #6
def ask(a,b=1,c=‘ok‘):
pass
ask(‘hello‘)
ask(‘hello‘,2)
ask(‘hello‘,2,‘yes‘)
ask(b=2,a=‘hello‘)
ask(‘hello‘,c=‘yes‘)
#ask(a=1,2,‘3‘) #出错
#可变长参数传递
def foo(a,*b):
print(type(a)) #str
print(type(b)) #tuplle
foo(‘hello‘,1,2,3,4)
def sum(*a):
total = 0
for i in a:
total += i
print(total)
sum(1,2) #3
sum(1,2,3) #6
sum(1,2,3,4) #10
#参数是字典
def foo(a, *b, **c):
print(a) #hello
print(b) #1,2,3,4
print(c) # {cn=‘china‘,us=‘america‘}
foo(‘hello‘,1,2,3,4,cn=‘china‘,us=‘america‘)
#高阶函数:参数是函数的函数
def add(a,b):
return a + b
def minus(a,b):
return a - b
def foo(x, y, f):
return f(x,y)
print(foo(1,2,add))
print(foo(1,2,minus))
x = 0 # Global变量
def m1():
#global x
x = 1 #Enclosing变量
def m2():
nonlocal x
x = 2 #Local变量
print(x) #2
m2()
print(x) #2
m1()
print(x) #0
#匿名函数
func = lambda x,y: x + y
func(1,2)
(lambda x,y:x + y)(1,2)
def foo():
for i in range(1,8):
print(‘第‘,i,‘步‘)
yield i*2
gen = foo()
print(type(gen)) #generator
gen.__next__() # 2
gen.__next__() #4
#定义装饰器
def xxx(f):
def yyy(a,b):
print(‘----‘)
return f(a,b)
return yyy
@xxx
def add(x,y):
return x+y
print(add(4,5)) # 9
print(add(1,2)) # 3
def outer(x):
def inner(y):
return x + y
return inner
f = outer(5)
f(3) # 8

Python基础(二)

标签:字符串   append   local   ica   format   height   查找   返回   方便   

原文地址:https://www.cnblogs.com/Jameszxx/p/9780017.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!