字典,集合,函数,global全局变量声明

本文介绍了Python中集合和字典的相关操作,包括通过if实现switch、字典的遍历、集合的定义与特性、增加和删除集合元素的方法、集合的交并补差以及函数和全局变量的声明。强调了集合作为无序且不重复数据类型的特性和操作,同时也探讨了数据类型的可变与不可变特性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.if实现switch

#!/usr/bin/env python
#coding=utf-8
while 1:
    num1 = input("num1:")
    oper = raw_input("操作符:")
    num2 = input("num2:")

    if oper == "+":
        print num1 + num2
    elif oper == "-":
        print num1 - num2
    elif oper == "*":
        print num1 * num2
    elif oper == "/":
        if num2 == 0:
            print "Error:分母为0"
        else:
            print num1 / num2
    else:
        print "操作符错误"

2.字典实现switch语句

#!/usr/bin/env python
#coding=utf-8
from __future__ import division

num1 = input("num1:")
oper = raw_input("操作符:")
num2 = input("num2:")


def add(num1,num2):
    return num1 + num2


def sub(num1,num2):
    return num1 - num2


def muilt(num1,num2):
    return num1 * num2


def div(num1,num2):
    if num2 == 0:
        print "分母为0,参数错误"
    else:
        return num1 / num2


dict = {
    "+": add,
    "-": sub,
    "*": muilt,
    "/": div,
}

if oper in dict:
    print dict[oper](num1, num2)
else:
    print "error"

3.字典的遍历

favourite_places = {
    "fentiao":['Xi\'an','Hangzhou'],
    'laoli':['Xianyang','Hanzhong']
}

for name in favourite_places:     ##先遍历key --定义为name
    print '\n' + name.title() + "\'s favourite places are"
    for place in favourite_places[name]:   ##再遍历values 定义place
        print place

4.集合是不重复的数据类型

集合s={1,2,3,4,5,1,2,3}

In [1]: s = {1,2,3,4,5,1,2,3}

In [2]: print type(s)
<type 'set'>

In [3]: print s
set([1, 2, 3, 4, 5])
4.1集合的定义,同元组列表一样,集合元素的数据类型不同,但不能存在列表,字典

这里写图片描述

s= {1,’hello’,’1L’,’1+3j’} 合法的集合
s= {1,’hello’,’1L’,’1+3j’,(1,2,3)} 集合里边可以存在元组

In [9]: type(s)
Out[9]: set

In [10]: print s
set([1, ‘hello’, ‘1+3j’, ‘1L’, (1, 2, 3)])

定义一个空集合s = set()
In [17]: s1 = set()

In [18]: print type(s1)
<type 'set'>

In [19]: 
4.2集合的一些特性:集合是无序的数据类型,这样就不会有索引, 切片, 重复,连接这些特性,但支持成员操作符
s = {91,2,3,15,89}
print s
s.add(80)
print s

执行结果

set([91, 89, 2, 3, 15])
set([2, 3, 15, 80, 89, 91])
集合是可迭代的对象, 因此支持for循环遍历元素;
s = {91,2,3,15,89}
print s
for i in s:
    print i,     ##加逗号输出不换行

执行结果:

set([91, 89, 2, 3, 15])
91 89 2 3 15        ##遍历无序

5.集合的基本操作—增加集合元素

5.1增加集合元素*.add() ###其中括号内可以是元组,字符串,基本数据类型,但不能是列表和字典
s = set()
s.add(1)
print s
s.add((1,2,3))
print s
s.add('hello')
print s

执行结果:

set([1])
set([1, (1, 2, 3)])
set([1, 'hello', (1, 2, 3)])
5.2修改集合元素*.update() 其中括号内可以是元组,字符串,列表,但不能是字典和基本数据类型
s = set()
s.update((1,2,3))
print s
s.update('hello')
print s
s.update([3,2,6])
print s
s.update({'a','b','c'})
print s

执行结果

set([1, 2, 3])
set([1, 2, 3, 'e', 'h', 'l', 'o'])
set([1, 2, 3, 'e', 6, 'h', 'l', 'o'])
set(['a', 1, 2, 3, 'e', 6, 'h', 'c', 'l', 'o', 'b'])
5.3删除集合元素*remove(),括号内元素及其类型载集合中要存在,否则报错KeyError:
s = {1,2,3,(5,6,7)}
s.remove(1)
print s
s.remove((5,6,7))
print s

执行结果

set([3, 2, (5, 6, 7)])
set([3, 2])
5.4*.pop()随即删除集合中元素,括号内不跟参数,否则报错TypeError:
s = {1,2,3,(5,6,7)}
s.pop()
print s

执行结果

set([1, 2, (5, 6, 7)])
5.5*.discard()括号内跟集合元素,删除集合中指定元素,不加元素报错TypeError,所跟元素集合中不存在,则不操作,不报错
s = {1,2,3,(5,6,7)}
s.discard(2)
print s
s.discard((5,6,7))
print s

执行结果

set([3, 1, (5, 6, 7)])
set([3, 1])
5.6*.copy()括号不跟参数,用于集合的复制
s1 = {1,2,3}
s2=s1.copy()
print s2

执行结果

set([1, 2, 3])

6.集合的交并补差

方法一:

        &    求两集合交集
        |     求两集合补集  
        -    求两集合差题   其中-号取前集合元素
        ^    对等差分  
实验:
s1 = {1,2,3}
s2 = {1,3,4}
print s1 & s2
print s1 | s2
print s1 - s2
print s1 ^ s2

执行结果

set([1, 3])
set([1, 2, 3, 4])
set([2])
set([2, 4])

方法二:

s1.issubset(s2)    ##判断s1是否是s2的子集,返回值布尔型
s1.issuperset(s2)  ##判断s1是否是s2的真子集,返回值布尔型                        
s1.difference(s2)  ##求s1和s2的集合的不同                       
s1.intersection    ##求s1和s2的交集 
s1.union           ##求s1和s2的并集 
s1.isdisjoint      ##自己看说明                  
s1 = {1,2,3}
s2 = {1,3,4}
print s1.intersection(s2)
print s1.union(s2)
print s1.difference(s2)

执行结果

set([1, 3])
set([1, 2, 3, 4])
set([2])

7.函数

python中如果函数无返回值, 默认返回None;
def 函数名(形参):
函数体
return 返回值



定义了一个函数
def fun(*args): # 形式参数
print args
调用函数
fun(“python”, 12, 0) # 实参


必选参数 def fun(name):
默认参数 def fun(name = “python”):
def fun(name=’python’):
print name

fun()

可变参数—-> *args args是元组类型



def fun(name,age,**kwargs): —-> **kwargs **kwargs是元组类型
print name,age, kwargs


参数组合时: 必选 > 默认参数 > 可变参数 > 关键字参数
def fun(a, b=0, *c, **d):
print a, b, c, d

fun(1, 2, 4, 5, 6, 7, c=3, x=2, z=2)



函数定义实验

#!/usr/bin/env python
# coding=utf-8
useinfo = {
    'root':{
        'name':'root',
        'passwd':'root',
        'gender':'M',
        'age':'19',
        'email':'qq@.com'
    }
}
info = """
                           用户管理系统
            1.注册
            2.登陆
            3.删除用户
            4.查看用户信息
            5.退出
"""
print info
def creatuser():
    print "注册系统界面".center(50, "*")
    username = raw_input("注册名:")
    if username in useinfo:
        print "%s 用户存在" % username
    else:
        passwd = raw_input("注册密码:")
        gender = raw_input("性别M/F:")
        if gender == "":
            gender = None
        age = raw_input("年龄:")
        if age == "":
            age = None
        email = raw_input("邮箱:")
        if email == "":
            email = None
        useinfo[username] = {
            'name': username,
            'passwd': passwd,
            'gender': gender,
            'age': age,
            'email': email,
        }

def login():
    trycount = 0
    while trycount < 3:
        trycount += 1
        print "欢迎进入登陆界面".center(50, "*")
        username = raw_input("登陆用户:")
        if username not in useinfo:
            print "没有%s该用户,清注册" % username
            break
        else:
            passwd = raw_input("登陆密码:")
            if passwd == useinfo[username]['passwd']:
                print '登陆成功'
                break
            else:
                print '密码错误'
    else:
        print "密码错误输入大于3次"

def deluser():
    usedel = raw_input("想删除的用户:")
    if usedel not in useinfo:
        print  "%s该用户不存在:" % usedel
    else:
        passwddel = raw_input("请输入密码:")
        if passwddel not in useinfo[usedel]['passwd']:
            print "删除%s该用户的密码不正确" % usedel
        else:
            print "删除%s用户成功" % usedel


def catuser():
    usercheck = raw_input("请输入要查看用户名:")
    if usercheck not in useinfo:
        print "无%s用户" % usercheck
    else:
        cat = useinfo.get(usercheck)
        print cat

while 1:
    choice = raw_input("请选择:")
    if choice == '1':
        creatuser()
    elif choice == "2":
        login()
    elif choice == '3':
        deluser()
    elif choice == '4':
        catuser()
    elif choice == '5':
        print 'bye'
        exit(0)

8.global全局变量声明

# 函数的作用域
 a = 10
 def fun():
     a = 100
 fun()
 print a

执行结果为10,fun()调用时没有打印,即使打印调用输出也是None

a = 10

变量声明:

a = 10
def fun():
    # # 声明a是全局变量
    global  a
    a = 100
    # global a = 100


fun()
print a

执行结果

a = 100

9.小结

数值类型: int, long, float, complex, bool
str, list, tuple, dict, set

可变数据类型: list, dict, set 数据一旦发生变化,不会在内存中开辟一个新的存储空间来存储新的对象,如set集合

In [67]: set
Out[67]: {1, 2, 3, 9, ('A', 'a')}

In [68]: id(set)
Out[68]: 42678392

In [69]: id(set)
Out[69]: 42678392

In [70]: set
Out[70]: {1, 2, 3, 9, ('A', 'a')}

In [71]: id(set)
Out[71]: 42678392

In [72]: set.pop()
Out[72]: 3

In [73]: set
Out[73]: {1, 2, 9, ('A', 'a')}

In [74]: id(set)
Out[74]: 42678392

In [75]: 
如此操作行不通,变量地址没有改变
list1 = [1,2,3,4,5]               
    list1[0]=10           
    print list1
    --->>[10, 2, 3, 4, 5]
-------------------------------
    d = {"a":1,"b":2}
    d1=d.update(c=3)
    print d1      ##印不出数据
    --->>None
--------------
    d = {"a":1,"b":2}
    d.update(c=3)
    print d      ##ok
    ----->>
    d = {"a":1,"c":3,"b":2}
不可变数据类型:tuple,str 数据一旦发生变化,就会在内存中开辟一个新的存储空间用于存储新的对象,原来的变量名会指向一个新的存储地址,如元组t和t1
In [77]: t =(1,2,3,4)

In [78]: id(t)
Out[78]: 44086560

In [79]: t1=t[::-1]

In [80]: t1
Out[80]: (4, 3, 2, 1)

In [81]: id(t1)
Out[81]: 44086472

In [82]: 
更改后的元组由于存储地址发生改变,可以赋给新的变量
        t =(1,2,3,4)
    t1=t[::-1]
    print t1
    ---->>(4,3,2,1)

可迭代的数据类型:str, list, tuple, dict, set

  ------- 可以for循环遍历元素;

不可迭代数据类型:

  ------不可以for循环遍历元素;

有序的数据类型:str, list, tuple,这类数据类型支持支持索引, 切片, 连接, 重复,成员操作符特性;

无序的数据类型:set,dict, 不支持索引, 切片, 连接, 重复,仅支持成员操作符;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值