python初级学习(二)

python初级学习(二)

一:列表构建栈的数据结构

info = """
            栈的管理
        1). 入栈
        2). 出栈
        3). 获取栈顶元素
        4). 栈长度
        5). 栈是否为空
        6). 退出

"""

stack = []

# stack = ['a', 'b', 'c']


while True:
    print info
    choice = raw_input('请输入选择:')  # 1, 2, 3
    if choice == '1':
        item = raw_input("入栈元素:")
        stack.append(item)
        print "%s 元素入栈成功!" %(item)

    elif choice == '2':
        # if stack:
        # 如果栈不为空, 执行xx操作;
        if stack != []:
            item = stack.pop()
            print "%s 出栈成功!" %(item)
        else:
            print "栈为空"
    elif choice == '3':
        if stack != []:
            print "栈顶元素为", stack[-1]
        else:
            print "栈为空"
    elif choice == '4':
        print  len(stack)
    elif choice == '5':
        if stack != []:
            # 打印不换行, print xxx,
            print "栈元素为",
            for i in stack:
                print i,
        else:
            print "栈为空"
    elif choice == '6':
        exit()
    else:
        print  "请输入正确的选项!"

二:列表构建队列的数据结构

队列: 入队, 出队, 队头, 队尾, 队长度, 队是否为空

info = """
            队列的管理
        1). 入队
        2). 出队
        3). 对头元素
        4). 队尾元素
        5). 队长度
        6). 队是否为空
        7).退出

"""

stack = []

# stack = ['a', 'b', 'c']


while True:
    print info
    choice = raw_input('请输入选择:')  # 1, 2, 3
    if choice == '1':
        item = raw_input("入队元素:")
        stack.append(item)
        print "%s 元素入队成功!" %(item)

    elif choice == '2':
        # if stack:
        # 如果队列不为空, 执行xx操作;
        if stack != []:
            item = stack.pop()
            print "%s 出队成功!" %(item)
        else:
            print "队列为空"
    elif choice == '3':
        if stack != []:
            print "队首元素为", stack[0]
        else:
            print "栈为空"
    elif choice == '4':
        if stack != []:
            print "队尾元素为", stack[-1]
        else:
            print "栈为空"
    elif choice == '5':
        print  len(stack)
    elif choice == '6':
        if stack != []:
            # 打印不换行, print xxx,
            print "栈元素为",
            for i in stack:
                print i,
        else:
            print "栈为空"
    elif choice == '7':
        exit()
    else:
        print  "请输入正确的选项!"

三:元组tuple(带了紧箍咒的列表)

1.1 为什么需要元组?

比如:打印用户的姓名
userinfo1 = “fentiao 4 male”
userinfo[0:7]
结论:字符串中操作提取姓名/年龄/性别的方式不方便,诞生元组.

1.2元组的定义

  • 定义空元组 tuple = ()
  • 定义单个值的元组 tuple = (fentiao,)
  • 一般的元组 tuple = (fentiao, 8, male)
  • 一个元素的元组 tuple = (1,)

1.3元组的特性

  • 不能对元组的值任意更改;
  • 对元组分别赋值,引申对多个变量也可通过元组方式分 别赋值

执行操作并思考
为什么可以改变元组的值呢?

1.4元组的操作

元组也属于序列,可执行的操作如下: 索引、切片、重复、连接和查看长度

  • 元组的嵌套
t6 = (1, 1.7, 1L, "hello", True, 1+3j, [1,2,3,4], (1,2,3))
print t6, type(t6)
  • 索引
print t6[0], t6[-1]
  • 索引里面的索引
print t6[-1][0]
  • 切片
print t6[::-1] # 反转元组
print t6[1:]    # 去掉元组的第一个元素
  • 重复
print t6 * 3
  • 连接
print  (1,2,3) + (1,3,4)
  • 成员操作符
print 'hello' in t6
print 'hello' not in t6
stack = []
#if后面跟bool类型;
 bool(stack) :
           stack = [], False
           stack = [1,2,3]  True
 #如果stack列表中有值, 执行的内容;
#if stack:
if stack != []:
    print "have item"
else:
    print "no item"
t = ()
if t:
#if t != ():
    print t
else:
    print "empty"

1.5元组的方法

  • t = (1,2,3,1,2,3)

    value值出现的次数;
    print t.count(1) # 2

    value值的索引
    print t.index(2) # 1

注意:

元组时可变数据类型吗? 不是可变数据类型;
t[0] = 10 # 执行报错, 不能对元组重新赋值;
print t

元组是可迭代数据类型, 可以for循环遍历每一个元素;
for i in t:

touple内置方法

  • cmp zip
    print cmp((1,2,3), (1,2,3,4))

    hosts = ['172.25.254.1', '172.25.254.2','172.25.254.3','172.25.254.4']
    ports = [22, 80, 3306, 21]
    print zip(hosts, ports)
  • 枚举enumerate, 每一个i是一个元组,(索引值, 元组元素)
for i,j in enumerate(hosts):
    print i,j

元组应用场景

print "%s:%s:%d" %('hello', 'world', 3306)

变量值交换

x = 1
y = 2
x,y = y,x

#
1. 先开辟一片内存空间, 存储元组, 元组内容(y,x) (2,1)
2. x,y = (2,1)
3. x = (2,1)[0]
4. y = (2,1)[1]

print x,y

元组案例

goods = [
    ('apple', 200),
    ('computer', 4000),
]

#for, enumerate
商品编号 货物名称 货物价格
001 apple 200
002computer4000

print "商品编号\t货物名称\t货物价格"

for gid,info in enumerate(goods):
    print "%.3d\t%s\t%s" %(gid+1,info[0], info[1])

四:字典

1.1为什么需要字典类型?

list1 = [“name”, “age”, “gender”]
list2 = [“fentiao”, 5, “male”]
zip(list1, list2)
//通过zip内置函数将两个列表结合,help(zip)
[(‘name’, ‘fentiao’), (‘age’, 5), (‘gender’, ‘male’)]为什么需要字典类型?
list2[0]
//在直接编程时,并不能理解第一个索引表示姓名
‘fentiao’
list2[name]
Traceback (most recent call last):
File “”, line 1, in
TypeError: list indices must be integers, not str
故字典是python中唯一的映射类型,key-value(哈希表),字典
对象是可变的,但key必须用不可变对象。

1.2字典的定义

键值对
Z     81(xxxxxxx)
key   value

1.3字典的创建

1.3.1 创建空字典

 dict
d = {}
print d, type(d)

d1 = dict()
print d1, type(d1)

1.3. 2 创建有元素的字典

d = {
   'key':'value'
 }



d2 = {
    'key1':'value1',
    'key2':'value2'
}

print d2, type(d2)


info = {
    'user1':'123',
    'user2':'345'
}


print 'user1' in info

通过key值获取value值;

print info['user1']

d4 = dict(user1='123', user2='456')
print d4, type(d4)

1.4字典的增删改查

1.4.1字典的增加

d = dict(a=1, b= 2, c=3)


d['d'] = 10
print d

#gengxin‘a’对应的value值;

d['a'] = 10
print d

#update:
如果key存在, 更新value值;
如果key不存在, 增加key-value值;

d.update(a=3, h=10)
print d


username = "hello"
password = '123'
d.update(username=password)
 print d

如果更新时,key值是一个 变量, 推荐使用下面的操作;

d.update({username:password})
print d

setdefault:

如果key存在, 不做操作;
如果key不存在, 增加key-value值;

d1 = dict(a=1, b=2)
d1.setdefault('c',10)
d1.setdefault('a',9)
print d1

1.4.2字典的删除

del d['a']
print d

pop(k[,d])

   1). 如果key存在, 返回value值;
   2). 如果key不存在;
           d存在时, 返回d;
           d不存在时, 直接报错
d.pop('b')
print d.pop('b',17)
print d.pop('e',17)

popitem随机删除key-value对;

d1 = dict(d=7, age=19,username='fentiao', password='123',a=2, e=19)
print d1.popitem()

clear: 清空字典

d1.clear()
print d1

删除字典在内存中的对象;

del d1

1.4.3字典的修改

d = dict(a=1, b= 2, c=3)

1.

d['a'] = 10
print d

2. update

d.update(b=10)
d.update({'c':0})
print d

1.4.4字典的查看

d = dict(a=1, b= 2, c=3)

查看字典的key值;

print d.keys()

iterator迭代器;节省内存;

print d.iterkeys()
print d.viewkeys()

查看key的value值;

print  d.values()
print d.itervalues()
print d.viewvalues()

查看字典的key-value对

print d.items()

请遍历字典的key-value值; 默认情况下, 遍历的时字典的key值;

for i in d:
    print i


for key,value in d.items():  # [('a', 1), ('c', 3), ('b', 2)]
    # key,value = ('a', 1)
    # key,value = ('c', 3)
    # key,value = ('b', 2)
    print "%s -> %s" %(key, value)

查看key是否存在

print 'a' in d
print d.has_key('a')

如果key存在, 返回对应的value值; 如果key存在, 返回None;

print d.get('a')
print d.get('e')

1.5字典的应用

d = dict(a=1, b=2)

print d.keys()

迭代器

a =  d.iterkeys()

类对象

f = d.viewkeys()
print f,type(f)

print dir(f)

面试: switch…case…..

python中不支持switch…case语句, python间接实现方式:
- if…elif…elif…else…
- 字典实现

num1 = input("NUM1:")
oper = raw_input("操作符(+,-,*,/):")
num2 = input("NUM2:")

d = {
    '+': num1 + num2,
    '-' : num1 - num2,
    '*' : num1 * num2,
    '/' : num1 / num2,

}
# if oper in d:
#     print d[oper]
# else:
#     print "请输入正确的操作符!"

print d.get(oper)
# if oper == '+':
#     print num1 + num2
# elif oper == '-':
#     print num1 - num2
# else:
#     print "清输入正确的操作符!"

1.6字典的代码排错

favourite_places = {
    'laoli': ['xian', 'hangzhou'],
    'fentiao':['hanzhong', 'xianyang']
}


for name in favourite_places:  # 'laoli'
    print "\n" + name.title() + "'s favourite place are:"

    for place in favourite_places[name]:  # [['xian', 'hangzhou'], ['hanzhong', 'xianyang']]
        # print place
        # place : list
        print place.title()

五:集合set

1.集合的定义

set = {}
set = {1,2,3}
set = {1,2,3,1,2,3}
set = {1,2,3,’hello’}
set = {1,2,3,’hello’,(1,2,3)}
set = {1,2,3,’hello’,(1,2,3),[1,2,3]}

2.set的应用场景

集合是一个无序的,不重复的数据组合。
• 列表去重
• 关系测试:如交集、差集、并集的关系测试
函数

s = {}
print type(s)

定义一个空集合

s1 = set()
print  type(s1)

字典可以转化为集合

d = dict(a=1, b=2, c=3)
print set(d)

集合是无序的数据类型;

s = {91, 2, 3, 12, 89}
s.add(13)
print s
s1 = {1, 2, 3, 4}

集合不支持的特性: 索引, 切片, 重复,连接
集合支持的特性: 成员操作符

print s[0], s[1:]

print s * 3

print s1 + s

print 1 in s1

集合是可迭代的对象, 因此支持for循环遍历元素;

s = {91, 2, 3, 12, 89}
for i in s:
    print i

3.集合的关系测试操作

  • • 交集: list_1.intersection(list_2)
  • • 并集: list_1.union(list_2)
  • • 差集: list_1.difference(list_2) , list_2.difference(list_1)
  • • 对等差分 list_1.symmetric_difference(list_2)
  • • 子集:list_1.issubset(list_2)
  • • 父集 list_1.issuperset(list_2)
  • • 有无交集 list_1.isdisjoint(list_2)
  • • 交集: list_1 & list_2
  • • 并集: list_1 | list_2
  • • 差集: list_1 - list_2 , list_2 - list_1
  • •对等差分:list_1 ^ list_2

4.集合的增删改查

4.1集合的添加

•s.add(1)
在集合中添加一项
•s.update([1,3,4])
在集合中添加多项,跟的参数应该是可迭代类型

4.2集合的删除

•s.remove(1)
删除集合中指定的元素
• s.pop()
随机删除集合中的某个元素,并返回删除的元素集合的其他操作
• len(s)
显示集合set的长度
•”1” in s
检测某元素是否为集合s的成员,返回布尔值集合的其他操作
• s.copy()
集合的浅拷贝,此处不深入研究,后面会说
•s.clear()
清空集合的所有元素

华为_调查问卷

import random

  #list, tuple, dict, set, str
  #排序功能?

s = set()
for i in range(input('N:')):
    s.add(random.randint(1,1000))
print sorted(s)



#li = list(s)
#li.sort()
#print li


#list(s).sort()

数值类型总结

数值类型: int, long, float, complex, bool

str, list, tuple, dict, set

可变数据类型: list, dict, set

不可变数据类型:

直接改变数据本身, 没有返回值;

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

不可迭代数据类型:

是否可以for循环遍历元素;

有序的数据类型:str, list, tuple,

无序的数据类型:

是否支持索引, 切片, 连接, 重复等特性;

六.函数

1.定义函数

  • • def关键字,依次写出函数名、括号、括号中的参数和冒号 :
  • • 在缩进块中编写函数体,函数的返回值用 return 语句返回。
def func():
pass
return

def 函数名(形参):
函数体
return 返回值

函数名(实参)

2.调用函数
Python 内置了很多有用的函数,我们可以直接调用:

  • • abs()
  • • cmp()
  • • 数据类型转换函数: int(), float(), str(),unicode(),bool()

3.理解函数名

  • •函数名与变量名类似,其实就是指向一个函数对象的引用;
  • •给这个函数起了一个“别名”:函数名赋给一个变量

4.空函数

  • • 定义一个什么事也不做的空函数,可以用 pass 语句;
  • • pass 可以用来作为占位符,还没想好怎么写函数的代码,就可以先放一个 pass ,让代码能运行起来
def nofunc():
pass

5.参数检查

  • •调用函数时,如果参数个数不对,Python 解释器会自动 检查出来,并抛出 TypeError;
  • • 如果参数类型不对,Python 解释器就无法帮我们检查。
  • • 数据类型检查可以用内置函数 isinstance 实现

6.函数返回值

函数可以返回多个值吗?那编写python程序,思考下:
定义一个函数func,传入两个数字,返回两个数字的
平均值与最大值。函数返回值

  • • 函数返回值用return关键字;
  • • 返回一个 tuple 可以省略括号;
  • • Python 的函数返回多值其实就是返回一个 tuple
  • • 函数执行完毕也没有 return 语句时,自动 return None

7.函数参数

•默认参数可以降低调用函数的难度。
定义一函数,计算x值的n次方。那如果计算x平方时只需要传入
x值时怎么解决?

默认参数注意事项:

•有多个参数时,变化大放前面,变化小的放后面;
•必选参数在前,默认参数在后默认参数

默认函数容易出错点:

试一试:先定义一个函数,传入一个 list,添加一个
END 再返回.默认参数
默认函数容易出错点:
试一试:先定义一个函数,传入一个 list,添加一个
END 再返回.

可变参数

  • 可变参数就是传入的参数个数是可变的,可以是 1 个、2 个
    到任意个,还可以是 0 个。*args
    以数学题为例子,给定一组数字 a,b,c……,
    请计算 a 2 + b 2 + c2+ ……
    如果已经有一个 list 或者 tuple,要调用一个可变参数怎么办?
  • Python 允许你在 list 或 tuple 前面加一个 * 号;
  • 把 list 或 tuple 的元素变成可变参数传进去;
largs = [1,2,3]
func(largs[0],largs[1],largs[2])
func(*largs)

关键字参数

•关键字参数允许你传入 0 个或任意个含参数名的参数;
•这些关键字参数在函数内部自动组装为一个 dict;
•关键字参数用**kwargs参数组合
•参数组合是指可以必选参数、 默认参数、 可变参数和关键
字参数一起使用。
•参数定义的顺序必须是:必选参数、 默认参数、可变参数和
关键字参数。

参数总结

• 必选参数
•默认参数:默认参数一定要用不可变对象
•可变参数:*args 是可变参数,args 接收的是一个 tuple
•关键字参数:**kw 是关键字参数,kw 接收的是一个
dict
•对于任意函数,都可以通过类似 func(*args, **kw) 的形式调用它

参数组合时: 必选 > 默认参数 > 可变参数 > 关键字参数

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)

用户管理系统

info = """"
###########user's administration###########
            1.add user
            2.login user
            3.logout user
            4.show users'messages
            5.exit
"""

userinfor = {
    'root': {
        'name': 'root',
        'password': 'root',
        'age': 18,
        'sex': 0,
        'email': '[email protected]'
    },
}





def createUser():
    user = raw_input("please input username:")
    if user in userinfor:
        print " %s exist!!!" % (user)
    else:
        password = raw_input("*please input password:")
        age = raw_input("*please input age:")
        sex = raw_input("please input sex:<0:male,1:female>")
        if not sex:
            sex = None
        email = raw_input("please input email:")
        if not email:
            email = None

        userinfor[user] = {
            'name': user,
            'password': password,
            'age': age,
            'sex': sex,
            'email': email
        }
        print "%s created!!!" % (user)


def userLogin():
    user = raw_input("please input your username:")
    if userinfor.has_key(user):
        password = raw_input("please input your password:")
        if userinfor[user]['password'] == password:
            print "%s logined" % (user)
        else:
            print "error:password doesn't match!!!"
    else:
        print "error:please create your username!!!"



def userLogout():
    user = raw_input("please input username:")
    if userinfor.has_key(user):
        password = raw_input("please input  password:")
        if userinfor[user]['password'] == password:
            userinfor.pop(user)
            print "%s has delet" % (user)
        else:
            print "error:password doesn't match!!!"
    else:
        print "error:please input currect username!!!"




def userView():
    print userinfor.items()


def main():
    print info
    while 1:
        choice = raw_input("*please input your choice:")
        if choice == '1':
            createUser()
        elif choice == '2':
            userLogin()
        elif choice == '3':
           userLogout()
        elif choice == '4':
            userView()
        elif choice == '5':
            exit(0)
        else:
            print 'error'



if __name__ == "__main__":
    main()

8.变量的作用域

  • • 局部变量:只能在函数内部使用的变量
  • • 全局变量:在整个程序中使用的变量
  • • global关键字:强制将局部变量转换为全局变量
#
# a = 10
# def fun():
#     a = 100
# print a




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




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


fun()
print a

判断质数

# def isPrime(n):
#     for i in range(2, n):
#         if n % i == 0:
#             return  False
#     else:
#         return True
#
#
#
# n = input('N:')
# print [i for i in range(2,n) if isPrime(i)]



# print [i+j for i in 'abc' for j in '123']
import os

print [i for i in os.listdir('/var/log/') if i.endswith('.log')]

七.迭代

判断数据类型是否可迭代?

- for i in 对象名:
- isinstance(对象名, Iterable)
from collections import Iterable


print isinstance(1, Iterable)
print isinstance(1L, Iterable)
print isinstance('hello', Iterable)
print isinstance((1,2,3,4), Iterable)
print isinstance([1,2,3,4], Iterable)
print isinstance({}, Iterable)
print isinstance({1,}, Iterable)




for i, j in [(1,9), (2,5), (3,7)]:
    # i,j = (1,9)
    # i,j = (2,5)
    # i,j = (3,7)
    print i, j


for i,j in enumerate('hello'):
    # i,j = (0,'h')
    # i,j = (1, 'e')
    # i,j = (2, 'l')
    # i,j = (3, 'l')
    print i,j

八.列表生成式

列表生成式:生成列表的公式;
“”“

对列表的每一个元素求平方;

1. 古老方法:

li = []
for i in range(10):
    li.append(i ** 2)
print li

列表生成式的方法:

print [i ** 2 for i in range(10)]

找出1-10之间所有的偶数;

print [i for i in range(1, 11) if i % 2 == 0]
print range(2, 11, 2)

找出1~1000之间所有的质数;

质数: 只能被1和它本身整除的数;

def isPrime(num):
    # 2是最小的质数;
    if num == 2: return True
    # 负数或者能被2整除的数, 不是质数;
    if num <= 1 or num%2 == 0: return False
    for i in range(3,num,2): ## 3~num-1
        # 如果num能被1或者它本身的其他数整除, 则不是质数;
        if num % i == 0:
            return False
    # 一直从3~num-1判断, 都没有被整除, 则是质数;
    else:
        return  True
n = input()
primes_li =  [i for i in range(1, n+1) if isPrime(i)]

count = 0

遍历1~n之间所有的质数;

for i in primes_li:
    # 如果n-i
    if n-i in primes_li and i <= n-i:
        print (i,n-i)
        count += 1
print count

2018携程春招题

题目描述:
对于一个十进制的正整数n,定义函数f(n)为其各个数的平方, 如:
f(13) = 1**2+3**2=10
f(207) = 2**2+0**2+7**2=53

下面给出三个正整数k,a,b,计算出有多少个正整数满足a<=n<=b且k*f(n)=n;

具体题目参考群里图片;

k = input()
a = input()
b = input()
def f(n):
    # 对于正整数每一位拆分,并求每一位的平方;
    # sum是求和
    return sum([int(i) ** 2 for i in str(n)])

def isOk(k,n):
    if k*f(n) == n:
        return True
    else:
        return False

li = [i for i in range(a,b+1) if isOk(k,i)]
print len(li)

猜你喜欢

转载自blog.csdn.net/liuyong1_/article/details/79806320
今日推荐