Python基础任务3

1. 字典

字典,是一系列键值对,每个键都与一个值相关联。键是不可变的,值可修改,在python中的标志是{}

⑴ 增加

dict['新增键k'] = 新增值v
dict.setdefault('k','v')

⑵ 删除

dict.pop('键')     #根据key删除键值对,有返回值
del dict['键']     #没有返回值
dict.itempop()     #随机删除某个键值对,删除的键值以元组的形式返回
dict.clear()       #清空字典

⑶ 修改

ditc2.update(dict1)    #将dict1所有键值对覆盖添加到dict2中(键相同则覆盖,没有就增加)
dict2 = {'name':'Lee','weight':98}   #直接带着键修改新值

⑷ 查找

dict.items()        #查看键值对
dict.keys()         #查看键
dict.values()       #查看值
dict['键']          #若没有该键值,会报错
dict.get('键','默认返回值')     #若没有该键值,会返回设定的默认返回值

2. 集合

set()集合是无序的不可重复的元素的集合。
集合的用法

3. 判断语句

⑴ 简单if语句

if conditional_test:     
	do something

if-else语句

age = 17
if age >= 18: 
	print("You are old enough to vote!")     
	print("Have you registered to vote yet?")  
else:      
	print("Sorry, you are too young to vote.")      
	print("Please register to vote as soon as you turn 18!")

if-elif-else语句

age = 12
if age < 4:      
	print("Your admission cost is $0.") 
elif age < 18:      
	print("Your admission cost is $5.") 
else:      
	print("Your admission cost is $10.")

4. 三目表达式

定义:三元运算是if-else 语句的快捷操作,也被称为条件运算。
结构:[on_true] if [expression] else [on_false]
示例:

x,y = 1,3
bigger = x if x>y else y

多层嵌套使用

a,b,c = 2,6,8 
max = a if a>b and a>c else (b if b>a and b>c else c)

5. 列表、集合和字典推导式

列表:[expr for val in collection if condition]
集合:{expr for val in collection if condition}
字典:{key_expr:value_expr for value in collection if condition}
等同于如下for循环:

result = []
for val in collection:
    if condition:
        result.append(expr)

嵌套列表推导式
列表推导式的for部分是根据嵌套的顺序,过滤条件放在最后。

some_tuples = [(1,2,3),(4,5,6),(7,8,9)]
flattened = [x for tup in some_tuples for x in tup]
print(flattened)

等价于下面的for循环语句:

flattened = []
for tup in some_tuples:
  for x in tup:
    flattened.append(x)

6. lambda表达式

定义:lambda 函数是一种快速定义单行的最小函数,又称匿名函数,可以用在任何需要函数的地方 。
结构:lambda 形参列表 : 函数返回值表达式语句
示例:

x = lambda a,b:a**b
print(x(3,6)) 

注意:所谓匿名函数,也就是说可以不需要命名,只是临时一用。

data =  list(range(10)) 
#列表元素自乘
print('自乘后:',list(map(lambda n:n*n ,data))) # 自乘后: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

6. 循环语句

⑴ for 语句

for循环是一种迭代循环机制。

for num in range(10,20):  # 迭代 10 到 20 之间的数字
   for i in range(2,num): # 根据因子迭代
      if num%i == 0:      # 确定第一个因子
         j=num/i          # 计算第二个因子
         print '%d 等于 %d * %d' % (num,i,j)
         break            # 跳出当前循环
   else:                  # 循环的 else 部分
      print num, '是一个质数'

⑵ while语句

while循环是条件循环,即在某条件下,循环执行某段程序。

current_number = 1 
while current_number <= 5:    
	print(current_number)    
	current_number += 1

⑶ break

break 语句可以跳出 for 和 while 的循环体。如果从 for 或 while 循环中终止,任何对应的循环 else 块将不执行。

for i in range(10):  
   if i == 5:
      break
   print ('数字为 :', i)
num = 8               
while num > 0:             
   print ('数字为 :', num)
   num -= 1
   if num == 5:
      break

⑷ continue

continue语句被用来告诉Python跳过当前循环块中的剩余语句,然后继续进行下一轮循环。

for i in range(10):  
   if i == 5:
      continue
   print ('数字为 :', i)
num = 0  
while num < 10: 
	num += 1      
	if num % 2 == 0:          
		continue
	print(num)

⑸ pass

pass是空语句,是为了保持程序结构的完整性,它不做任何事情,一般用做占位语句。

while True:
	pass  # 等待键盘中断 (Ctrl+C)

参考文章:
https://www.cnblogs.com/zhangyux/p/5968069.html
http://www.runoob.com/python/python-while-loop.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值