Python(三)

来源:互联网 发布:emlog博客源码 编辑:程序博客网 时间:2024/05/29 17:51

一、列表(可变数据类型)

这里写图片描述

1.列表的定义

   列表是打了激素的数组,数组只能存储同种类型的数据,而列表像一个仓库,存储不同类型的数据.例:   l = []                          ##定义一个空列表l = [1]                         ##定义有一个元素的列表l = [1,(1,2),"hello",[1,2]]代码展示:In [1]: l=[]                     ##打印列表名的花,会将整个列表原模原样的输出In [2]: print l[]In [3]: l=[1]In [4]: print l[1]In [5]: l=[1,(1,2),"hello",[1,2]]In [6]: print l[1, (1, 2), 'hello', [1, 2]]In [7]: print l[0]                    ##只有打印列表的索引号才可以打印出列表内的内容,[0]为第一个元素1In [8]: print l[-1]                   ##[-1]为倒数第一个元素[1, 2]

2.列表的特性

1)索引 从0开始,依次增加,对应于特定唯一的元素 例如:l = [1,(1,2),"hello",[1,2]]           ##各元素的索引号依次为:0,1,2,3In [9]: print l[1]                    ##[1]为第二个元素(1, 2)
2)切片格式:列表名[x:y:z]    其中,x表示切片开始的索引号的位置;y减去1表示切片结束的索引号的位置;z表示步长举例:In [23]: l=[1,(1,2),"hello",[1,2]]In [24]: l[1:3]Out[24]: [(1, 2), 'hello']
3)重复规则:只需要在字符串后面添加上*n,n表示重复的次数举例:l = [1,(1,2),"hello",[1,2]]In [10]: print l[-1]*2[1, 2, 1, 2]
4)连接格式:直接用"+"连接即可将两个字符串即可完成拼接举例:In [12]: str1=["hello"]In [13]: str2=["world"]In [14]: str=str1+str2               In [15]: print str['hello', 'world']

3. 列表的方法

1)增加1>l.append()                                //末尾追加单个元素举例:In [17]: l=["hello"]In [18]: l.append("world")In [19]: print l['hello', 'world']In [20]: l.append(["hello","fentiao"])In [21]: print l['hello', 'world', ['hello', 'fentiao']2>l.extend()                                 //末尾追加多个元素举例:In [23]: l.extend(["hello","fentiao"])In [24]: print l['hello', 'world', ['hello', 'fentiao'], 'hello', 'fentiao']3>l.insert()                                  //指定位置插入单个元素举例:In [25]: l.insert(0,"westos")In [26]: print l['westos', 'hello', 'world', ['hello', 'fentiao'], 'hello', 'fentiao']
2)删除1> l.remove()     //删除第一个遇到的元素值 举例: In [28]: print l['westos', 'hello', 'world', ['hello', 'fentiao'], 'hello', 'fentiao']In [29]: l.remove("hello")In [30]: print l['westos', 'world', ['hello', 'fentiao'], 'hello', 'fentiao2> l.pop()        //删除指定的索引所在的元素,默认删除最后一个 举例: [默认情况]In [37]: print l['westos', 'hello', 'world', ['hello', 'fentiao'], 'hello', 'fentiao']In [38]: l.pop()Out[38]: 'fentiao'In [39]: print l['westos', 'hello', 'world', ['hello', 'fentiao'], 'hello'][指定删除]In [40]: l.pop(0)Out[40]: 'westos'In [41]: print l['hello', 'world', ['hello', 'fentiao'], 'hello']
3)修改:直接根据索引进行修改        格式:列表名[索引号]="修改后的字符串"     //l[0]="value"    举例:In [41]: print l['hello', 'world', ['hello', 'fentiao'], 'hello']In [42]: l[0]="hello1"In [43]: print l['hello1', 'world', ['hello', 'fentiao'], 'hello']
4)查看列表信息1>l.count()       //查找某个元素出现的次数举例:In [43]: print l['hello1', 'world', ['hello', 'fentiao'], 'hello']In [44]: l.count("hello")Out[44]: 12>l.index()       //查找某个元素最小的索引举例:In [46]: print l['hello', 'world', ['hello', 'fentiao'], 'hello']In [47]: l.index("hello")Out[47]: 0
5)排序- l.sort()      //列表排序- l.reverse()       //列表逆转
6) 内置方法min()max()len()zip()enumerate()sum()sorted()reversed()

4. 列表的实战

1)问题:通过列表实现堆栈的数据结构,堆栈是一个后进先出的数据结构分析:step1: 定义一个空列表:l = []step2:各个功能的分别实现        welcome to stack mangementp(U)sh:入栈p(O)p:出栈(V)iew:查看栈(Q)uit:退出系统
代码展示:#!/usr/bin/env python#coding:utf-8"""file:zhan.pydate:9/1/179:29 PMauthor:hxdesc:zhan"""print '''                    Welcome to stack management            ---------------------------------------------             U...................................p(U)sh             O....................................p(O)p             V...................................(V)iew             Q...................................(Q)uit             Enter the choice that you want~~~            ----------------------------------------------'''strstack = []inputstr = ""while True:    choice = raw_input("Please input the choice U / O / V / Q :")    if choice == "U":        inputstr = raw_input("Please input the string:").strip()        strstack.append(inputstr)        print "push successfully"    elif choice == "O":        while len(strstack) != 0:            strstack.pop()            print "pop successfully"            break        else:            print "stack is empty~"    elif choice == "V":        for i in strstack:            print i,        print "\r"    elif choice == "Q":        print "Enjoy yourself~"        exit(0)    else:        print "Please input the choice U / O / V / Q : \n try again~~"        continue

测试结果:
这里写图片描述

2)问题:通过列表实现队列的数据结构,队列是一个先进先出的数据结构。分析:与前面的堆栈相比较,只是pop有所不同,改变索引值即可实现
代码展示:#!/usr/bin/env python#coding:utf-8"""file:queue.pydate:9/1/179:29 PMauthor:hxdesc:queue"""print '''                    Welcome to queue management            ---------------------------------------------             U...................................p(U)sh             O....................................p(O)p             V...................................(V)iew             Q...................................(Q)uit             Enter the choice that you want~~~            ---------------------------------------------'''strqueue = []inputstr = ""while True:    choice = raw_input("Please input the choice U / O / V / Q :")    if choice == "U":        inputstr = raw_input("Please input the string:").strip()        strqueue.append(inputstr)        print "push successfully"    elif choice == "O":        while len(strqueue) != 0:            strqueue.pop(0)            print "pop successfully"            break        else:            print "stack is empty~"    elif choice == "V":        for i in strqueue:            print i,        print "\r"    elif choice == "Q":        print "Enjoy yourself~"        exit(0)    else:        print "Please input the choice U / O / V / Q : \n try again~~"        continue

测试结果:
这里写图片描述

二、 元组(不可变数据类型)

这里写图片描述

1. 元组的定义:

 t = ()                    //空元组 t = (1,)                  //元组只有一个元素时,加",",t=(1),t是int类型; t = (1,2,(1,2),[1,2])     //可以包含任何类型的数据结构

通过type可以查看数据类型
这里写图片描述

2. 元组的特性

1)不可以修改元素内容,t[0]="westos",直接报错

这里写图片描述

2)分别赋值,name,age = ("westos",10)

这里写图片描述

3)索引

这里写图片描述

4)切片举例:In [12]: t=(1,"hello",(1,2),["welcome"])In [20]: t[0:2]Out[20]: (1, 'hello')
5)重复举例:In [21]: t[0:2]*3Out[21]: (1, 'hello', 1, 'hello', 1, 'hello')
6)连接举例:In [22]: t[0:1]+t[1:2]Out[22]: (1, 'hello')

3. 元组的方法

1) t.count()        //计算某个元素出现的次数

这里写图片描述

2) t.index()        //返回某个值的最小索引

这里写图片描述

二、试一试

(2017-网易-笔试编程题)-字符串练习

  • 题目描述:

小易喜欢的单词具有以下特性:
1.单词每个字母都是大写字母
2.单词没有连续相等的字母
3.单词没有形如“xyxy”(这里的x,y指的都是字母,并且可以相同)这样的子序列,子序列可能不连续。
例如:
小易不喜欢”ABBA”,因为这里有两个连续的’B’
小易不喜欢”THETXH”,因为这里包含子序列”THTH”
小易不喜欢”ABACADA”,因为这里包含子序列”AAAA”
小易喜欢”A”,”ABA”和”ABCBA”这些单词
给你一个单词,你要回答小易是否会喜欢这个单词。

  • 输入描述:
    输入为一个字符串,都由大写字母组成,长度小于100

  • 输出描述:
    如果小易喜欢输出”Likes”,不喜欢输出”Dislikes”

示例1 :

输入    AAA输出    Dislikes
代码:date:9/2/1712:22 AMauthor:hxdesc:like or dislike"""str=raw_input("Please input string:")def con1(str):    return str.isupper()def con2(str):    for i in range(len(str)-1):        if str[i]==str[i+1]:            return False    return Truedef main(str):    if con1(str) and con2(str):        return "likes"    else:        return "dislikes"print main(str)

这里写图片描述

(2017-腾讯-在线编程题)

  • 题目描述:

给定一个正整数,编写程序计算有多少对质数的和等于输入的这个正整数,并输出结果。输入值小于1000。
如,输入为10, 程序应该输出结果为2。(共有两对质数的和为10,分别为(5,5),(3,7))

  • 输入描述:
    输入包括一个整数n,(3 ≤ n < 1000)

  • 输出描述:
    输出对数

  • 示例1 :

输入:    10输出:    2
代码:#!/usr/bin/env python#coding:utf-8"""file:zhishu.pydate:9/1/1711:28 PMauthor:hxdesc:zhishu"""num=input("input:")sum=0if num<1 and num>1000:   print "Error input!"   exit(0)def isprime(num):    for i in range(2,num):        if num % i == 0:            return False    return Truefor i in range(2,num/2):    if isprime(i) and isprime(num-i):        sum+=2print sum

这里写图片描述

(2017-好未来-笔试编程题)–列表练习

  • 题目描述:
    输入两个字符串,从第一字符串中删除第二个字符串中所有的字符。例如,输入”They are students.”和”aeiou”,则删除之后的第一个字符串变成”Thy r stdnts.”

  • 输入描述:
    每个测试输入包含2个字符串

  • 输出描述:
    输出删除后的字符串

  • 示例1:

输入    They are students.    aeiou输出    Thy r stdnts.
代码:#!/usr/bin/env python#coding:utf-8"""file:replace.pydate:9/2/1712:16 AMauthor:hxdesc:replace"""str1=raw_input("Please input str1:")str2=raw_input("Please input str2:")for i in str2:    str1 = str1.replace(i,"")print str1

这里写图片描述

(2017-好未来-在线编程题)

  • 题目描述:
    输入两个整数 n 和 m,从数列1,2,3…….n 中随意取几个数,使其和等于 m ,要求将其中所有的可能组合列出来

  • 输入描述:

每个测试输入包含2个整数,n和m

  • 输出描述:
    按每个组合的字典序排列输出,每行输出一种组合

  • 示例1 :

输入:    5 5输出:    1 4    2 3    5

(2017-去哪儿网-在线编程)

  • 题目描述:

18位身份证的编码规则是:
前1、2位数字表示:所在省(直辖市、自治区)的代码
第3、4位数字表示:所在地级市(自治州)的代码
第5、6位数字表示:所在区(县、自治县、县级市)的代码;
第7—14位数字表示:出生年、月、日;
第15、16位数字表示:所在地的派出所的代码;
第17位数字表示性别:奇数表示男性,偶数表示女性;
第18位数字是校检码,用来检验身份证的正确性。
用户在输入身份证的过程中经常会输入错误,为了方便用户正确输入需要在输入过程中对用户的输入按照 6+8+4 的格式进行分组,实现一个方法接收输入过程中的身份证号,返回分组后的字符

  • 输入描述:
    输入数据有多行,每一行是一个输入过程中的身份证号

  • 输出描述:
    分组后的字符串

  • 示例1

输入:    5021    502104 198803    5021041988033084    502104198803308324输出:    5021    502104 198803    502104 19880330 84    502104 19880330 8324
#!/usr/bin/env python#coding:utf-8"""file:ID.pydate:2017-09-02 5:17 PMauthor:hxdesc:身份证号码按照格式输出"""s=raw_input("input your ID:")l=len(s)if l<=6:    print selif l<=14:    print s[:6],s[6:]                    ##切片操作实现elif l<=18:    print s[:6],s[6:14],s[14:]else:    print "Error"