python基础---元组、集合、字典、if语句

一、元组

元组的定义:使用()存储元素,元组中的数据不可变,可以使用索引访问列表元素,不可修改元组中单个元素,会提示类型错误

元组使用及访问,修改会报错

dimensions = (200,50)
    print(dimensions[0]) #元组查看数据
    print(dimensions[1])
    #dimensions[0] = 150  元组不可修改,报类型错误TypeError
    for dimension in dimensions: #元组遍历
        print(dimension)

元组中元素虽然不可修改,但是可以全部重新赋值

    dimensions = (200,50)
    for dimension in dimensions: #元组遍历
        print(dimension)
    dimensions = (400,150)
    for dimension in dimensions:
        print(dimension)

二、字典

字典是一系列键值对,与键关联的值可以是数字、字符串、列表、字典,字典是一种动态结构,可以随时在其中添加键值对
  1. 1、访问字典中的值
alien_0 = {'color':'green','point':5}
    print(alien_0['color']) #通过键获取字典中的值
    print(alien_0['point'])

2.2、添加键值对

  alien_0 = {'color':'green','point':5}
    alien_0['x_point'] = 20
    alien_0['y_point'] = 0
    print(alien_0) #{'color': 'green', 'point': 5, 'x_point': 20, 'y_point': 0}

2.3、创建一个空字典

   aline = {}
    aline['color'] = 'green'
    aline['point'] = 5
    print(aline)

2.4、修改字典中的值

例子一:

aline = {}
    aline['color'] = 'green'
    aline['point'] = 5
    print(aline) #{'color': 'green', 'point': 5}
    aline['color'] = 'yellow'
    print(aline) #{'color': 'yellow', 'point': 5}

例子二:

alien_0 = {'x_position':0,'y_position':25,'speed':'medium'}
    x_increment = 0
    print("Original x-position "+str(alien_0['x_position']))
    if alien_0['speed']  == 'slow':
        x_increment = 1
    elif alien_0['speed'] == 'medium':
        x_increment = 2
    elif alien_0['speed'] == 'fast':
        x_increment = 3
    alien_0['x_position'] = alien_0['x_position']+x_increment
    print(alien_0['x_position'])

2.5、删除键值对

del +通过键获取的值

  alien_0 ={'color':'green','point':5}
    print(alien_0) #{'color': 'green', 'point': 5}
    del alien_0['point']
    print(alien_0)  #{'color': 'green'}

2.6、字典的遍历

1.遍历所有键值对 字典.items()

 user_0 = {
        'username': 'efermi',
        'first': 'enrico',
        'last': 'fermi',
    }
    for key,value in user_0.items(): #key value变量不是固定的,可修改
        print("key "+key)
        print("value "+value)

2、遍历字典中所有的键、遍历字典中所有的值

  for key in user_0.keys():
        print(key)
    for value in user_0.values():
        print(value)

2.7、字典嵌套,字典列表

将字典存储在列表中

#嵌套 字典列表,将字典存在列表中
    alien_0 = {'color':'green','points':5}
    alien_1 = {'color':'yellow','points':10}
    alien_2 = {'color':'red','points':15}
    aliens = [alien_0,alien_1,alien_2]
    for alien in aliens:
        for value in alien.values():
            print(value)

2.8、在字典里面嵌套列表,遍历字典中列表值

将列表存储在字典中

pizza = {
        'crust' : 'thick',
        'topping':['mushrooms','extra mushroom'],
    }
    print("You order a "+pizza['crust']+"-crust pizza"+"whith the following toppings:")
    for topping in pizza['topping']:
        print("\t"+topping )

例子二:

 favorite_language = {
        'jen':['python','ruby'],
        'sarah':['c'],
        'edward':['ruby','go'],
        'phil':['python','haskell'],
    }
    for name,languages in favorite_language.items():
        print(name+" favorite language is ")
        for language in languages:
            print("\t"+language)

改进:如果喜欢的语言大于1种就遍历,否则直接输出

  favorite_language = {
        'jen':['python','ruby'],
        'sarah':['c'],
        'edward':['ruby','go'],
        'phil':['python','haskell'],
    }
    for name,languages in favorite_language.items():
        print(name+" favorite language is ")
        if len(languages) > 1:
            for language in languages:
                 print("\t"+language)
        else:
            print("\t"+languages[0])

将字典存储在字典时,内容遍历

   users = {
        'aeinstein':{
            'first':'albert',
            'last':'einstein',
            'lociation':'pricenton',
        },
        'mcurie':{
            'first':'marie',
            'last':'curie',
            'lociation':'paris',
        }
    }
    for username,user_info in users.items():
        print("\n Username "+username)
        full_name = user_info['first']+" "+user_info['last']
        location = user_info['lociation']
        print("\t Full name: "+full_name.title())
        print("\t Lociation: "+location.title())

三、集合

3.1、什么是集合

  • 集合(Set)是一个无序的不重复的元素序列
  • 常用来对俩个列表进行交并差的处理
  • 集合和列表一样,支持所有数据类型

3.2、集合和列表的区别

  • 列表是有序可重复的,列表无序且不可重复,相同内容无法在添加到列表内,
  • 列表是用于数据的使用,集合是用于数据的交集并集差集的获取
  • 列表有索引,集合没有索引
  • 符号的话列表[],集合是{}

3.3、集合的创建

通过set()函数来创建集合,不能使用{}来创建空集合

a_set = set() 创建了一个空集合

a_set = set([1,2,3]) 传入列表或元组

b_set = {1,2,3} 传入元素

c_set={} 这是种错误表示方法,会以为是字典

3.4、集合的创建、初始化以及给列表去重

  a = set() #通过set创建集合
    print(a)  #<class 'set'>
    print(type(a))
    a1 = set(['python','java','mysql','oracle']) #使用set通过列表初始化
    print(a1)
    # a2 = {[1,2,3],[4,5]} #这种被认为是字典报TypeError
    # print(a2)
    # a3={{'key':'value'}}   #这种被认为是字典报TypeError
    # print(a3)
    a4 = {(1,2,3)}  #集合中元素可为元组、数字、字符串
    print(a4)
    a5 =['java','python','java']
    a6=set(a5)
    print(a6) #给列表去重

3.5、集合的增删改

add函数:用于集合中添加一个元素,如果集合中已存在该元素则该函数不执行

用法:set.add(item) item是要添加到集合中的元素、无返回值

update函数:加入一个新的集合(或列表、元组、字符串)如新集合内的元素在原著中存在则无视

用法:set.update(iterable) iterable 集合(或列表、元组、字符串)、无返回值

remove函数:将集合中的某个元素删除,如元素不存在将会报错

用法:set.remove(item) item当前集合的一个元素 无返回值,直接作用于原集合

clear函数:清空集合中的所有元素

用法:set.clear() 无参数无返回值

del函数 del set 直接删除后print(set) 报错NameError: name ‘array_set’ is not defined 彻底删除

  array_set = set(["abc",6])
    print(array_set)
    #添加
    array_set.add("hello")
    print(array_set)
    a_tuple = ('a','b','c')
    array_set.add(a_tuple)
    print(array_set) #{'hello', ('a', 'b', 'c'), 6, 'abc'} 存在形式是元组
    #添加元组
    array_set.update(a_tuple)
    print(array_set)  #{'a', 'abc', 6, 'hello', 'b', ('a', 'b', 'c'), 'c'} #元组内容被拆开
    #删除
    array_set.remove(('a','b','c'))
    array_set.remove('a')
    print(array_set)
    #清除删除集合内容
    array_set.clear()
    print(array_set)
    #彻底删除
    del array_set

重要说明:
集合无法通过索引获取元素
集合无获取元素的任何方法、只能通过循环遍历
集合只是用来处理列表或者元组的一种临时类型,他不适合存储与运输

3.6、集合的差集

1、什么是差集?
a、b俩个集合,由所有属于a且不属于b的元素组成的集合叫做a与b的差集

2、difference的功能
返回集合的差集,即返回的集合元素包含在第一个集合中,但不包含在第二个集合中但不包含在第二个集合中的方法参数
用法:a_set.difference(b_set) 参数b_set:当前集合需要对比的集合
返回值:a_set与b_set的差集

set_num1 = {1,2,3,4,5}
    set_num2 = {1,2,3,6,7}
    num = set_num1.difference(set_num2)
    print(num)

3.7、集合的并集

set_num1 = {1,2,3,4,5}
    set_num2 = {1,2,3,6,7}
    num = set_num1.difference(set_num2)
    num_all = set_num1.union(set_num2)
    print(num)  # 取set_num1与set_num2的差集{4, 5}
    print(num_all) # 取set_num1与set_num2的并集  {1, 2, 3, 4, 5, 6, 7}

3.8、判断俩个集合中是否有相同元素

isdisjoint功能:判断俩个集合是否包含相同元素,没有返回True,有返回False

isdisjoint用法: a_set.isdisjoint(b_set) 返回值是一个布尔值True或者False

    set_num1 = {1,2,3,4,5}
    set_num2 = {1,2,3,6,7}
    b= set_num1.isdisjoint(set_num2)
    print(b) #False

3.9、集合的交集

集合a与集合b相同的元素,叫做集合a和集合b的交集

text = {'小明','小红','小丽'}
res = {'小丽','小张','小红'}
result = text.intersection(res)
print(result) #取交集 {'小红', '小丽'}

四、if语句

示例:车列表,遇到bmw,全部大写,其他只有首字母大写

cars= ['audi','bmw','subaru','toyota']
for car in cars:
    if car == 'bmw':
        print(car.upper())
    else:
        print(car.title())

4.1判断符号

使用==测试俩者是否相等,对于字符串检查相等时候考虑大小写,可使用upper(),lower()等,不相等时可使用!=来判断

常用的判断符号:==,!= , >= , <= , >, <

使用and检查多个条件 (age_0 >=21) and (age_1 >= 21) ,俩个条件都满足为True

使用or 检查多个条件 (age_0 >=21) and (age_1 >= 21),至少有一个条件满足就能通过整个测试

4.2、查询值是否包含在特定列表里 in

requested_toppings = ['mushrooms','onions','pineapple']
    if('mushrooms' in requested_toppings):
        print("蘑菇在食谱里")

4.3、查询特定的值不在列表里 not in

banned_users = ['andrew','carolina','david']
    user = 'marie'
    if user not in banned_users:
        print(user.title()+" ,you can post a response if you wish")

4.4、if-else语句

 #if-else语句
    age = 17
    if age >= 18:
        print("you are old enough to vote")
    else:
        print("Sorry, you are too young to vote")

4.4、if-elif-else

    age = int(input("please input your age"))
    if age < 4 :
        print("you are for free")
    elif age >=4 and age <= 18:
        print("you need pay 5 doller")
    else:
        print(" you need pay 10 doller")

简洁的方式:

age = int(input("please input your age"))
    price = 0
    if age < 4 :
        price = 0
    elif age >=4 and age <= 18:
        price = 5
    else:
        price = 10
    print("you need pay ",price)

可根据需要使用任意数量的elif代码块、也可直接省略else代码块

4.5、检查列表不为空:

  request_toppings = []
    if request_toppings:
        for request_topping in request_toppings:
            print("Adding "+request_topping)
        print("\nFinished making your pizza!")
    else:
        print("Are you sure ,you want a plain pizza")

4.6、使用多个列表

    available_toppings = ['mushrooms','olives','green peppers','pepperoni','pineapple','extra cheese']
    request_toppings = ['mushrooms','french fries','extra cheese']
    for request_topping in request_toppings:
        if request_topping in available_toppings:
            print("Adding "+request_topping+" .")
        else:
            print("Sorry, we don't have "+request_topping)
    print("\nFinished making your pizza!")
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值