• 列表元组字典字符串操作


    The reason why people give up so quickly is because they look at how far they still have to go, instead of how far they have come

    第二章

    1.列表的操作                                  2.元组的操作

    3.字符串操作                                  4.字典的操作

    ♣列表的操作:

    列表:列表用于存储数据、操作数据的最常见的一种数据类型,可以支持数据的增、删、改、查

    定义列表:

    1 #! /user/bin/env python
    2 #_-_coding:utf-8_-_
    3 import os,sys
    4 some=["cat","dog","monkey"]

    操作列表:

    >追加zoo.append

    1 #! /user/bin/env python
    2 #_-_coding:utf-8_-_
    3 import os,sys
    4 zoo=["cat","dog","monkey"]
    5 zoo.append("donkey")
    6 print(zoo)
    #结果是:['cat', 'dog', 'monkey', 'donkey'],追加到列表的最后

     >切片zoo[:]

     1 #! /user/bin/env python
     2 #_-_coding:utf-8_-_
     3 import os,sys,getpass
     4 zoo=["cat","dog","monkey","donkey","chiken"]
     5 print(zoo[0])#只获取第一个值,精确的值,非列表
     6 print(zoo[1:])#获取第二个及以后的全部值,以列表的显示展示
     7 print(zoo[-1])#获取最后一个值,精确的值,非列表
     8 print(zoo[1:-1])#获取下标1到-1的值,不包括-1,俗称顾头不顾尾
     9 print(zoo[0::2])#2的意思是每隔2个取一次值
    10 print(zoo[::2])#同zoo[0::2] ,凡是带有:的都是切取的列表
    11 
    12 '''结果是:
    13 cat
    14 ['dog', 'monkey', 'donkey', 'chiken']
    15 chiken
    16 ['dog', 'monkey', 'donkey']
    17 ['cat', 'monkey', 'chiken']
    18 ['cat', 'monkey', 'chiken']
    19 
    20 '''

     >插入zoo.insert(i,x)

     1 #! /user/bin/env python
     2 #_-_coding:utf-8_-_
     3 import os,sys,getpass
     4 zoo=["cat","dog","monkey","donkey","chiken"]
     5 zoo.insert(2,"Tiger")#2表示的是插入的位置
     6 zoo.insert(10,"Tiger")#如果下脚标不存在,则在最后一个位置插入 10不存在,则在接近10 即最大脚标位置插入
     7 print(zoo)
     8 '''
     9 ['cat', 'dog', 'Tiger', 'monkey', 'donkey', 'chiken', 'Tiger']
    10 '''

    >修改zoo[0]

     1 #! /user/bin/env python
     2 #_-_coding:utf-8_-_
     3 import os,sys,getpass
     4 
     5 zoo=["cat","dog","monkey","donkey","chiken"]
     6 zoo[0]='dog'#修改下脚标为0的值,可见列表中可存储相同的值
     7 print(zoo)
     8 '''结果是:
     9 ['dog', 'dog', 'monkey', 'donkey', 'chiken']
    10 '''

    >删除del、pop、remove

     1 #! /user/bin/env python
     2 #_-_coding:utf-8_-_
     3 import os,sys,getpass
     4 zoo=["cat","dog","monkey","donkey","chiken"]
     5 del zoo[2] #删除下脚标为2的值,monkey没了
     6 print(zoo)
     7 zoo.remove("dog")#删除指定的值,dog又没了
     8 print(zoo)
     9 zoo.pop()#删除最后一个值,参数默认是-1,chiken没了
    10 print(zoo)
    11 zoo.pop(-2)#参数是-2,删除的是倒数第二个值
    12 print(zoo)
    13 del zoo
    14 print(zoo)#会报错,提示zoo未被定义,其实是删除了整个列表
    15 '''结果是:
    16 ['cat', 'dog', 'donkey', 'chiken']
    17 ['cat', 'donkey', 'chiken']
    18 ['cat', 'donkey']
    19 ['donkey']
    20 '''

     >扩展 extend()

     1 #! /user/bin/env python
     2 #_-_coding:utf-8_-_
     3 import os,sys,getpass
     4 zoo=["cat","dog","monkey","donkey","chiken"]
     5 bird=["Smew","Cuckoo","Partridge","Peafowl"]
     6 zoo.extend(bird)#将bird中全部值扩展到zoo中
     7 print(zoo)
     8 '''结果:
     9 ['cat', 'dog', 'monkey', 'donkey', 'chiken', 'Smew', 'Cuckoo', 'Partridge', 'Peafowl']
    10 '''

    >统计zoo.count("")

    1 #! /user/bin/env python
    2 #_-_coding:utf-8_-_
    3 import os,sys,getpass
    4 zoo=["cat","dog","monkey","donkey","chiken","cat"]
    5 count=zoo.count("cat")#统计元素cat在zoo列表中的个数
    6 print(count)
    '''结果:
    2
    '''

     >排序sort()、翻转reverse

     1 #! /user/bin/env python
     2 #_-_coding:utf-8_-_
     3 import os,sys,getpass
     4 zoo=["cat","dog","monkey","donkey","chiken","Cat","1","!#@",""]
     5 zoo.sort()#排序,默认排序规则是特殊字符,数字,大写字母A-Z,小写字母a-z等开头的排序,即ASICLL编码表顺序排列
     6 print(zoo)
     7 zoo.reverse()#翻转列表
     8 print(zoo)
     9 '''结果:
    10 ['!#@', '1', 'Cat', 'cat', 'chiken', 'dog', 'donkey', 'monkey', 'xe9x99x88']
    11 '''

     >下脚标查询index()

     1 #! /user/bin/env python
     2 #_-_coding:utf-8_-_
     3 import os,sys,getpass
     4 zoo=["cat","dog","monkey","donkey","chiken","cat","1","!#@",""]
     5 lic0=zoo.index("cat")#查找cat的下脚标,只能显示第一个查到的下脚标
     6 lic1=zoo.index("cat",1)#从下脚标1这个位置查找cat的下脚标
     7 lic2=zoo.index("cat",1,6)#从下脚标1到6之间查找cat的下脚标
     8 #lic3=zoo.index("cat",1,4)#报错,提示ValueError: 'cat' is not in list
     9 print(lic0,lic1,lic2)
    10 '''结果:
    11 (0, 5, 5)
    12 '''

    >拷贝copy()

     1 #! /user/bin/env python
     2 #_-_coding:utf-8_-_
     3 import os,sys,getpass,copy
     4 a=[1,2]
     5 b=[a,3]
     6 print(b)
     7 c=copy.copy(b)#浅浅的copy
     8 d=copy.deepcopy(b)#俗称深copy
     9 print(c)#[[1, 2], 3]
    10 print(d)#[[1, 2], 3]
    11 a[1]=10
    12 print(c)#通过copy()过来的值变化了  [[1, 10], 3]
    13 print(d)#通过deepcopy()的值没有变化 [[1, 2], 3]

    ♣元组

    元组:以小括号显示,与列表类似的类型,元组一旦创建,值便不可被修改,又叫只读列表。有两个属性:count()、index()

    1 #! /user/bin/env python
    2 #_-_coding:utf-8_-_
    3 zoo=("dog","cat","monkey")#元组是只读列表,只有count、index属性

     ♣字典

    字典一种key - value 的数据类型,字典的特点是:1.key是唯一的,即天生去重 2.无序

    1 #! /user/bin/env python
    2 #_-_coding:utf-8_-_
    3 import os,sys,getpass
    4 zoo_dict={"1":["cat","dog"],
    5                "2":["donkey","monkey"],
    6                "3":["bird","tiger"]
    7 }
    8 print(zoo_dict)    

     >增加

     1 #! /user/bin/env python
     2 #_-_coding:utf-8_-_
     3 import os,sys,getpass
     4 zoo_dict={"1":["cat","dog"],
     5                "2":["donkey","monkey"],
     6                "3":["bird","tiger"]
     7 }
     8 print(zoo_dict)
     9 zoo_dict["3"]=["chiken","Smew"]#增加key=3的值,如果存在key=3,那么更新value值。
    10 zoo_dict["4"]=["chiken","Smew"]#增加key=4的值
    11 print(zoo_dict)
    12 '''结果无序
    13 {'1': ['cat', 'dog'], '3': ['bird', 'tiger'], '2': ['donkey', 'monkey']}
    14 {'1': ['cat', 'dog'], '3': ['bird', 'tiger'], '2': ['donkey', 'monkey'], '4': ['chiken', 'Smew']}
    15 '''

     >删除

     1 #! /user/bin/env python
     2 #_-_coding:utf-8_-_
     3 import os,sys,getpass
     4 zoo_dict={"1":["cat","dog"],
     5                "2":["donkey","monkey"],
     6                "3":["bird","tiger"],
     7 "4":["bird","tiger"]
     8 }
     9 print(zoo_dict)
    10 zoo_dict.pop("1")#删除了key=1的值,标准的删除
    11 print(zoo_dict)
    12 del zoo_dict["2"]#另一种删除方式
    13 print(zoo_dict)
    14 zoo_dict.popitem()#随机删除一组数字
    15 #del zoo_dict["5"]#删除不存在的key值报错
    16 print(zoo_dict)
    17 '''结果:
    18 {'1': ['cat', 'dog'], '3': ['bird', 'tiger'], '2': ['donkey', 'monkey'], '4': ['bird', 'tiger']}
    19 {'3': ['bird', 'tiger'], '2': ['donkey', 'monkey'], '4': ['bird', 'tiger']}
    20 {'3': ['bird', 'tiger'], '4': ['bird', 'tiger']}
    21 {'4': ['bird', 'tiger']}
    22 '''

    >修改

     1 #! /user/bin/env python
     2 #_-_coding:utf-8_-_
     3 import os,sys,getpass
     4 zoo_dict={"1":["cat","dog"],
     5                "2":["donkey","monkey"],
     6                "3":["bird","tiger"],
     7 "4":["bird","tiger"]
     8 }
     9 zoo_dict["4"]=["tiger","bird"]#有则修改
    10 zoo_dict["5"]=["tiger","bird"]#无则增加
    11 print(zoo_dict)
    12 '''
    13 {'1': ['cat', 'dog'], '3': ['bird', 'tiger'], '2': ['donkey', 'monkey'], '5': ['tiger', 'bird'], '4': ['tiger', 'bird']}
    14 '''

     >查找

    #! /user/bin/env python
    #_-_coding:utf-8_-_
    import os,sys,getpass
    zoo_dict={"1":["cat","dog"],
                   "2":["donkey","monkey"],
                   "3":["bird","tiger"],
    "4":["bird","tiger"]
    }
    print(zoo_dict["4"])#查找key=4的值
    print(zoo_dict.get("4"))#查找key=4的值
    print(zoo_dict.get("6"))#查找key=6的值 没有也不报错,没有显示None
    print(zoo_dict["5"])#查找key=5的值,没有则报错
    '''
    Traceback (most recent call last):
      File "D:/python/newDay/Day1/Day2/liebiao.py", line 12, in <module>
        print(zoo_dict["5"])#查找key=5的值,没有则报错
    KeyError: '5'
    ['bird', 'tiger']
    ['bird', 'tiger']
    None
    '''

    >字典嵌套

     1 #! /user/bin/env python
     2 #_-_coding:utf-8_-_
     3 import os,sys,getpass
     4 animal={
     5 "zoo_dict":{"1":["cat","dog"],
     6                "2":["donkey","monkey"],
     7                "3":["bird","tiger"],
     8                "4":["bird","tiger"]},
     9 "zoo_dict2":{"1":["cat","dog"],
    10                "2":["donkey","monkey"],
    11                "3":["bird","tiger"],
    12                "4":["bird","tiger"]}
    13 }
    14 animal["zoo_dict"]["1"]="[cat]"#修改字典中的值
    15 print(animal)
    16 animal["zoo_dict"]["1"]+="cater"#拼接字符串
    17 print(animal)
    18 '''
    19 {'zoo_dict2': {'1': ['cat', 'dog'], '3': ['bird', 'tiger'], '2': ['donkey', 'monkey'], '4': ['bird', 'tiger']}, 'zoo_dict': {'1': '[cat]', '3': ['bird', 'tiger'], '2': ['donkey', 'monkey'], '4': ['bird', 'tiger']}}
    20 {'zoo_dict2': {'1': ['cat', 'dog'], '3': ['bird', 'tiger'], '2': ['donkey', 'monkey'], '4': ['bird', 'tiger']}, 'zoo_dict': {'1': '[cat]cater', '3': ['bird', 'tiger'], '2': ['donkey', 'monkey'], '4': ['bird', 'tiger']}}
    21 '''

     >常用:

     1 #! /user/bin/env python
     2 #_-_coding:utf-8_-_
     3 import os,sys,getpass
     4 
     5 zoo_dict={"1":["cat","dog"],
     6                "2":["donkey","monkey"],
     7                "3":["bird","tiger"],
     8                "4":["bird","tiger"]}
     9 zoo_dict2 = {"4": ["cat", "dog"],
    10             "5": ["donkey", "monkey"],
    11             "6": ["bird", "tiger"],
    12             "7": ["bird", "tiger"]}
    13 print(zoo_dict.values())#获取字典的value
    14 print(zoo_dict.keys())#获取字典的key
    15 print(zoo_dict.setdefault("1","cat"))
    16 zoo_dict.update(zoo_dict2)#把zoo_dict2的key和value添加到zoo_dict里,注意:zoo_dict2中的key与zoo_dict中的key相同时,则能添加
    17 print(zoo_dict)
    18 print(zoo_dict.items())#字典迭代,生成以列表格式
    19 '''
    20 [['cat', 'dog'], ['bird', 'tiger'], ['donkey', 'monkey'], ['bird', 'tiger']]
    21 ['1', '3', '2', '4']
    22 ['cat', 'dog']
    23 {'1': ['cat', 'dog'], '3': ['bird', 'tiger'], '2': ['donkey', 'monkey'], '5': ['donkey', 'monkey'], '4': ['cat', 'dog'], '7': ['bird', 'tiger'], '6': ['bird', 'tiger']}
    24 [('1', ['cat', 'dog']), ('3', ['bird', 'tiger']), ('2', ['donkey', 'monkey']), ('5', ['donkey', 'monkey']), ('4', ['cat', 'dog']), ('7', ['bird', 'tiger']), ('6', ['bird', 'tiger'])]
    25 '''

     ♣字符串操作

    引用自:http://www.cnblogs.com/zhxiang/p/3385242.html

      1 Python 字符串操作(string替换、删除、截取、复制、连接、比较、查找、包含、大小写转换、分割等)   
      2      
      3      
      4     去空格及特殊符号  
      5     s.strip() .lstrip() .rstrip(',')   
      6      
      7     复制字符串  
      8     #strcpy(sStr1,sStr)   
      9     sStr= 'strcpy'   
     10     sStr = sStr  
     11     sStr= 'strcpy'   
     12     print sStr   
     13      
     14     连接字符串  
     15     #strcat(sStr1,sStr)   
     16     sStr= 'strcat'   
     17     sStr = 'append'   
     18     sStr+= sStr   
     19     print sStr  
     20      
     21     查找字符  
     22     #strchr(sStr1,sStr)   
     23     sStr= 'strchr'   
     24     sStr = 's'   
     25     nPos = sStr1.index(sStr)   
     26     print nPos   
     27      
     28     比较字符串  
     29     #strcmp(sStr1,sStr)   
     30     sStr= 'strchr'   
     31     sStr = 'strch'   
     32     print cmp(sStr1,sStr)  
     33      
     34     扫描字符串是否包含指定的字符  
     35     #strspn(sStr1,sStr)   
     36     sStr= '1345678'   
     37     sStr = '456'   
     38     #sStrand chars both in sStrand sStr   
     39     print len(sStrand sStr)  
     40      
     41     字符串长度  
     42     #strlen(sStr1)   
     43     sStr= 'strlen'   
     44     print len(sStr1)   
     45      
     46     将字符串中的大小写转换  
     47     #strlwr(sStr1)   
     48     sStr= 'JCstrlwr'   
     49     sStr= sStr1.upper()   
     50     #sStr= sStr1.lower()   
     51     print sStr  
     52      
     53     追加指定长度的字符串  
     54     #strncat(sStr1,sStr,n)   
     55     sStr= '1345'   
     56     sStr = 'abcdef'   
     57     n = 3 
     58     sStr+= sStr[0:n]   
     59     print sStr  
     60      
     61     字符串指定长度比较  
     62     #strncmp(sStr1,sStr,n)   
     63     sStr= '1345'   
     64     sStr = '13bc'   
     65     n = 3 
     66     print cmp(sStr1[0:n],sStr[0:n])   
     67      
     68     复制指定长度的字符  
     69     #strncpy(sStr1,sStr,n)   
     70     sStr= ''   
     71     sStr = '1345'   
     72     n = 3 
     73     sStr= sStr[0:n]   
     74     print sStr  
     75      
     76     将字符串前n个字符替换为指定的字符  
     77     #strnset(sStr1,ch,n)   
     78     sStr= '1345'   
     79     ch = 'r'   
     80     n = 3 
     81     sStr= n * ch + sStr1[3:]   
     82     print sStr  
     83      
     84     扫描字符串  
     85     #strpbrk(sStr1,sStr)   
     86     sStr= 'cekjgdklab'   
     87     sStr = 'gka'   
     88     nPos = -1 
     89     for c in sStr1:   
     90          if c in sStr:   
     91              nPos = sStr1.index(c)   
     92              break   
     93     print nPos   
     94      
     95     翻转字符串  
     96     #strrev(sStr1)   
     97     sStr= 'abcdefg'   
     98     sStr= sStr1[::-1]   
     99     print sStr  
    100      
    101     查找字符串  
    102     #strstr(sStr1,sStr)   
    103     sStr= 'abcdefg'   
    104     sStr = 'cde'   
    105     print sStr1.find(sStr)   
    106      
    107     分割字符串  
    108     #strtok(sStr1,sStr)   
    109     sStr= 'ab,cde,fgh,ijk'   
    110     sStr = ','   
    111     sStr= sStr1[sStr1.find(sStr) + 1:]   
    112     print sStr  
    113      或者   
    114     s = 'ab,cde,fgh,ijk'   
    115     print(s.split(','))   
    116      
    117     连接字符串  
    118     delimiter = ','   
    119     mylist = ['Brazil', 'Russia', 'India', 'China']   
    120     print delimiter.join(mylist)   
    121     PHP 中 addslashes 的实现  
    122     def addslashes(s):   
    123          d = {'"':'\"', "'":"\'", "":"\", "\":"\\"}   
    124         return ''.join(d.get(c, c) for c in s)   
    125     s = "John 'Johny' Doe (a.k.a. "Super Joe")\"   
    126     print s   
    127     print addslashes(s)   
    128      
    129     只显示字母与数字  
    130     def OnlyCharNum(s,oth=''):   
    131          s = s.lower();   
    132         fomart = 'abcdefghijklmnopqrstuvwxyz013456789'   
    133         for c in s:   
    134             if not c in fomart:   
    135                  s = s.replace(c,'');   
    136          return s;   
    137     print(OnlyStr("a000 aa-b"))
    str

     总结:

      1 #! /user/bin/env python
      2 #_-_coding:utf-8_-_
      3 import os,sys,getpass,copy
      4 a=[1,2]
      5 b=[a,3]
      6 print(b)
      7 c=copy.copy(b)#浅浅的copy
      8 d=copy.deepcopy(b)#俗称深copy
      9 print(c)#[[1, 2], 3]
     10 print(d)#[[1, 2], 3]
     11 a[1]=10
     12 print(c)#通过copy()过来的值变化了  [[1, 10], 3]
     13 print(d)#通过deepcopy()的值没有变化 [[1, 2], 3]
     14 
     15 '''
     16 zoo_dict={"1":["cat","dog"],
     17                "2":["donkey","monkey"],
     18                "3":["bird","tiger"],
     19                "4":["bird","tiger"]}
     20 zoo_dict2 = {"4": ["cat", "dog"],
     21             "5": ["donkey", "monkey"],
     22             "6": ["bird", "tiger"],
     23             "7": ["bird", "tiger"]}
     24 print(zoo_dict.values())#获取字典的value
     25 print(zoo_dict.keys())#获取字典的key
     26 print(zoo_dict.setdefault("1","cat"))
     27 zoo_dict.update(zoo_dict2)#把zoo_dict2的key和value添加到zoo_dict里,注意:zoo_dict2中的key与zoo_dict中的key相同时,则能添加
     28 print(zoo_dict)
     29 print(zoo_dict.items())#字典迭代,生成以列表格式
     30 '''
     31 '''
     32 [['cat', 'dog'], ['bird', 'tiger'], ['donkey', 'monkey'], ['bird', 'tiger']]
     33 ['1', '3', '2', '4']
     34 ['cat', 'dog']
     35 {'1': ['cat', 'dog'], '3': ['bird', 'tiger'], '2': ['donkey', 'monkey'], '5': ['donkey', 'monkey'], '4': ['cat', 'dog'], '7': ['bird', 'tiger'], '6': ['bird', 'tiger']}
     36 [('1', ['cat', 'dog']), ('3', ['bird', 'tiger']), ('2', ['donkey', 'monkey']), ('5', ['donkey', 'monkey']), ('4', ['cat', 'dog']), ('7', ['bird', 'tiger']), ('6', ['bird', 'tiger'])]
     37 '''
     38 
     39 '''
     40 animal["zoo_dict"]["1"]="[cat]"#修改字典中的值
     41 print(animal)
     42 animal["zoo_dict"]["1"]+="cater"#拼接字符串
     43 print(animal)
     44 '''
     45 '''
     46 {'zoo_dict2': {'1': ['cat', 'dog'], '3': ['bird', 'tiger'], '2': ['donkey', 'monkey'], '4': ['bird', 'tiger']}, 'zoo_dict': {'1': '[cat]', '3': ['bird', 'tiger'], '2': ['donkey', 'monkey'], '4': ['bird', 'tiger']}}
     47 {'zoo_dict2': {'1': ['cat', 'dog'], '3': ['bird', 'tiger'], '2': ['donkey', 'monkey'], '4': ['bird', 'tiger']}, 'zoo_dict': {'1': '[cat]cater', '3': ['bird', 'tiger'], '2': ['donkey', 'monkey'], '4': ['bird', 'tiger']}}
     48 '''
     49 
     50 
     51 '''
     52 
     53 print(zoo_dict["4"])#查找key=4的值
     54 print(zoo_dict.get("4"))#查找key=4的值
     55 print(zoo_dict.get("6"))#查找key=6的值 没有也不报错,没有显示None
     56 print(zoo_dict["5"])#查找key=5的值,没有则报错
     57 '''
     58 '''
     59 Traceback (most recent call last):
     60   File "D:/python/newDay/Day1/Day2/liebiao.py", line 12, in <module>
     61     print(zoo_dict["5"])#查找key=5的值,没有则报错
     62 KeyError: '5'
     63 ['bird', 'tiger']
     64 ['bird', 'tiger']
     65 None
     66 '''
     67 
     68 '''
     69 zoo_dict["4"]=["tiger","bird"]#有则修改
     70 zoo_dict["5"]=["tiger","bird"]#无则增加
     71 print(zoo_dict)
     72 '''
     73 '''
     74 {'1': ['cat', 'dog'], '3': ['bird', 'tiger'], '2': ['donkey', 'monkey'], '5': ['tiger', 'bird'], '4': ['tiger', 'bird']}
     75 '''
     76 
     77 '''
     78 print(zoo_dict)
     79 zoo_dict.pop("1")#删除了key=1的值,标准的删除
     80 print(zoo_dict)
     81 del zoo_dict["2"]#另一种删除方式
     82 print(zoo_dict)
     83 zoo_dict.popitem()#随机删除一组数字
     84 #del zoo_dict["5"]#删除不存在的key值报错
     85 print(zoo_dict)'''
     86 '''结果:
     87 {'1': ['cat', 'dog'], '3': ['bird', 'tiger'], '2': ['donkey', 'monkey'], '4': ['bird', 'tiger']}
     88 {'3': ['bird', 'tiger'], '2': ['donkey', 'monkey'], '4': ['bird', 'tiger']}
     89 {'3': ['bird', 'tiger'], '4': ['bird', 'tiger']}
     90 {'4': ['bird', 'tiger']}
     91 '''
     92 
     93 '''
     94 print(zoo_dict)
     95 zoo_dict["3"]=["chiken","Smew"]#增加key=3的值,如果存在key=3,那么更新value值。
     96 zoo_dict["4"]=["chiken","Smew"]#增加key=4的值
     97 print(zoo_dict)'''
     98 '''结果无序
     99 {'1': ['cat', 'dog'], '3': ['bird', 'tiger'], '2': ['donkey', 'monkey']}
    100 {'1': ['cat', 'dog'], '3': ['bird', 'tiger'], '2': ['donkey', 'monkey'], '4': ['chiken', 'Smew']}
    101 '''
    102 
    103 #列表操作
    104 '''
    105 zoo=["cat","dog","monkey","donkey","chiken","cat","1","!#@","陈"]
    106 lic0=zoo.index("cat")#查找cat的下脚标,只能显示第一个查到的下脚标
    107 lic1=zoo.index("cat",1)#从下脚标1这个位置查找cat的下脚标
    108 lic2=zoo.index("cat",1,6)#从下脚标1到6之间查找cat的下脚标
    109 #lic3=zoo.index("cat",1,4)#报错,提示ValueError: 'cat' is not in list
    110 print(lic0,lic1,lic2)
    111 '''
    112 '''结果:
    113 (0, 5, 5)
    114 '''
    115 
    116 '''
    117 zoo.sort()#排序,默认排序规则是特殊字符,数字,大写字母A-Z,小写字母a-z等开头的排序,即ASICLL编码表顺序排列
    118 print(zoo)
    119 zoo.reverse()#翻转列表
    120 print(zoo)
    121 '''
    122 
    123 '''结果:
    124 ['!#@', '1', 'Cat', 'cat', 'chiken', 'dog', 'donkey', 'monkey', 'xe9x99x88']
    125 '''
    126 
    127 '''
    128 count=zoo.count("cat")#统计元素cat在zoo列表中的个数
    129 print(count)
    130 '''
    131 '''结果:
    132 2
    133 '''
    134 
    135 '''
    136 bird=["Smew","Cuckoo","Partridge","Peafowl"]
    137 zoo.extend(bird)#将bird中全部值扩展到zoo中
    138 print(zoo)'''
    139 '''结果:
    140 ['cat', 'dog', 'monkey', 'donkey', 'chiken', 'Smew', 'Cuckoo', 'Partridge', 'Peafowl']
    141 '''
    142 
    143 
    144 '''
    145 del zoo[2] #删除下脚标为2的值,monkey没了
    146 print(zoo)
    147 zoo.remove("dog")#删除指定的值,dog又没了
    148 print(zoo)
    149 zoo.pop()#删除最后一个值,参数默认是-1,chiken没了
    150 print(zoo)
    151 zoo.pop(-2)#参数是-2,删除的是倒数第二个值
    152 print(zoo)
    153 del zoo
    154 print(zoo)#会保存,提示zoo未被定义,其实是删除了整个列表
    155 '''
    156 '''结果是:
    157 ['cat', 'dog', 'donkey', 'chiken']
    158 ['cat', 'donkey', 'chiken']
    159 ['cat', 'donkey']
    160 ['donkey']
    161 '''
    162 
    163 '''
    164 zoo[0]='dog'#修改下脚标为0的值,可见列表中可存储相同的值
    165 print(zoo)
    166 '''
    167 '''结果是:
    168 ['dog', 'dog', 'monkey', 'donkey', 'chiken']
    169 '''
    170 
    171 '''
    172 zoo.insert(2,"Tiger")#2表示的是插入的位置
    173 zoo.insert(10,"Tiger")#如果下脚标不存在,则在最后一个位置插入 10不存在,则在接近10 即最大脚标位置插入
    174 print(zoo)
    175 '''
    176 
    177 '''
    178 ['cat', 'dog', 'Tiger', 'monkey', 'donkey', 'chiken', 'Tiger']
    179 '''
    180 '''
    181 print(zoo[0])#只获取第一个值,精确的值,非列表
    182 print(zoo[1:])#获取第二个及以后的全部值,以列表的显示展示
    183 print(zoo[-1])#获取最后一个值,精确的值,非列表
    184 print(zoo[1:-1])#获取下标1到-1的值,不包括-1,俗称顾头不顾尾
    185 print(zoo[0::2])#2的意思是每隔2个取一次值
    186 print(zoo[::2])#同zoo[0::2] ,凡是带有:的都是切取的列表
    187 '''
    188 '''结果是:
    189 cat
    190 ['dog', 'monkey', 'donkey', 'chiken']
    191 chiken
    192 ['dog', 'monkey', 'donkey']
    193 ['cat', 'monkey', 'chiken']
    194 ['cat', 'monkey', 'chiken']
    195 
    196 '''
    all

    ♣购物车小程序

      1 #!_-_coding:utf-8_-_
      2 #Author:chen
      3 import os,sys
      4 admin_user='admin.txt'#定义系统管理员文件
      5 use_user='user.txt'#定义用户文件
      6 
      7 admin=open(admin_user)
      8 use=open(use_user)
      9 admin_line=admin.readlines()
     10 use_line=use.readlines()
     11 
     12 admin.close()
     13 use.close()
     14 
     15 user_info={}#存放用户信息的字典
     16 user_money=[]
     17 newmoney=open("user.txt")
     18 money=newmoney.readlines()
     19 
     20 #print money
     21 for user_line in money:
     22     key_u=user_line.split()[0]
     23     Money_value=user_line.split()[1]
     24     user_info[key_u]=Money_value
     25 
     26 All_goods={}#存放商品的字典
     27 goods_value=[]
     28 goods_open=open("goods.txt")
     29 goods=goods_open.readlines()
     30 goods_open.close()
     31 #print(goods)
     32 for goods_line in goods:
     33     key=int(goods_line.split()[0])
     34     goods_value=goods_line.split()[1:]
     35     All_goods[key]=goods_value#这是字典的应用,key对应的value
     36 #print(All_goods[2][1])
     37 flag=True
     38 count=0
     39 while True:
     40     user_name=input("输入用户名:")
     41     while flag:
     42         for user_admin in admin_line:
     43             user_adm=user_admin.strip("
    ")
     44             if user_name == user_adm:#判断是否是管理员登录,是则进行下边操作
     45                 count += 1
     46                 print(All_goods)
     47                 choice_admin=input('【退出(q)】 | 【修改金额(编号)】 | 【添加(a)】')
     48                 if choice_admin=='q':
     49                     exit()
     50                 elif choice_admin=='a':
     51                     add_goods=input('商品名称:')
     52                     add_goods_funds=input("商品价格:")
     53                     newfile = open("goods.txt", "w")
     54                     for name, al in All_goods.items():
     55                         newfile.write("%s"" " % name)
     56                         for new_F in al:
     57                             new_name = new_F[:1]
     58                             new_value = new_F[1:]
     59                             # print(new_name,new_value)
     60                             newfile.write("%s""%s"" " % (new_name, new_value))
     61                         newfile.write("
    ")
     62                     newfile.write("%s"" " % str(len(All_goods)+1))
     63                     newfile.write("%s"" ""%s"" " % (add_goods, add_goods_funds))
     64                     newfile.write("
    ")
     65                     newfile.close()
     66                 elif choice_admin.isdigit():#判断管理员是否输入的是数字
     67                     choice_admin=int(choice_admin)#转换成int类型
     68                     if choice_admin<=key:
     69                         revise_fund = input("修改价格是:")
     70                         All_goods[choice_admin][1] =revise_fund
     71                         #print(All_goods)
     72                         newfile= open("goods.txt", "w")#打开商品文件,并赋予可写权限
     73                         for name, al in All_goods.items():#
     74                             newfile.write("%s"" " % name)
     75                             for new_F in al:
     76                                 new_name=new_F[:1]
     77                                 new_value = new_F[1:]
     78                                 #print(new_name,new_value)
     79                                 newfile.write("%s""%s"" " % (new_name,new_value))
     80                             newfile.write("
    ")
     81                         newfile.close()#文件的操作必须有关闭动作,否则,内容可能导致丢失
     82                         #continue
     83                     else:
     84                         print("不存在此商品,请重新选择:")
     85                         flag=True
     86                 else:
     87                     print("【33[91m 操作有误,请重新选择 33[0m】")#可以给字体颜色标红
     88                     #break
     89             elif user_name!=user_adm:#如果不是管理员登录,则进行下边的循环
     90                 for user_use in use_line:
     91                     user_u,user_fund=user_use.strip("
    ").split()#获取客户信息
     92                     if user_u==user_name:#判断是否是客户登录
     93                         count += 1
     94                         print(All_goods)
     95                         print("您的资金余额是:【%s】" % user_info[user_name])#调用字典,显示客户金额
     96                         choice_user=input('[退出(q) | 购买(编号)]')
     97                         #print("您的资金余额是:%s" % user_fund)
     98                         if choice_user=="q":
     99                             exit()
    100                         elif choice_user.isdigit():
    101                             choice_user=int(choice_user)
    102                             if choice_user<=key:#判断用户选择是否是存在的编号
    103                                #print("您购买的商品是:%s"%All_goods[choice_user][0])
    104                                #print(user_info[user_name],All_goods[choice_user][1])
    105                                user_info[user_name]=int(user_info[user_name])#用户金额转换成int
    106                                All_goods[choice_user][1]=int(All_goods[choice_user][1])#shangpin金额转换成int
    107                                if user_info[user_name]<All_goods[choice_user][1]:#比较用户金额和商品金额大小
    108                                    print("****您的金额不足***")
    109                                    break
    110                                else:
    111                                    user_info[user_name]=user_info[user_name]-All_goods[choice_user][1]#更新用户金额
    112                                    user_info[user_name] = str(user_info[user_name])
    113                                    newfile = open("user.txt", "w")#以可写方式打开文件
    114                                    for uname, al in user_info.items():
    115                                        newfile.write("%s"" "% uname)
    116                                        for new_F in al:
    117                                            new_value = new_F[0]
    118                                            # print(new_name,new_value)
    119                                            newfile.write("%s" % (new_value))#讲最新金额写入文件
    120                                        newfile.write("
    ")
    121                                    newfile.close()
    122                     elif count==0:
    123                          print("您还不是系统用户,请注册后再登录!")
    124                          exit()
    Shopping_Cart

    ♣文件的操作演示

    文件:

    zhao 1000
    qian 2000
    zhou 15000
    user.txt
     1 #! /user/bin/env python
     2 #_-_coding:UTF-8_-_
     3 import os,sys
     4 user={}#定义一个字典,用来存储数据
     5 user_file='user.txt'#定义要操作的文件
     6 open_user_file=open(user_file)#打开要操作的文件
     7 count=0
     8 #********下面是将文件中的内容存储到字典中***************
     9 while count<2:
    10     for user_line in open_user_file.readlines():#迭代该文件
    11         key_u=user_line.split()[0]#获取字典的key值
    12         Money_value=user_line.split()[1]#获取字典的value值
    13         user[key_u]=Money_value#将该文件中的内容存入uer{}字典中
    14         print(user)
    15         count+=1
    16 #**********下面是将数据写入文件*************************
    17 while count<5:
    18     open_new_file = open(user_file, 'w')#以可读的方式打开要写入的文件,可以是新文件,没有则自动创建
    19     for uname, al in user.iteritems():#迭代字典中的值(用户可对字典中的数据进行操作、修改)这里只演示存入文件
    20         count+=1
    21         open_new_file.write("%s"" ""%s"% (uname,al))#将数据写入文件,可以调整写入的样式,这里是key+空格+value
    22         open_new_file.write("
    ")#每个数据换行
    23 open_user_file.close()#必要的存入字典的文件
    24 open_new_file.close()#必要的关闭写入的文件

    好文章:

    http://www.cnblogs.com/heyongqi/p/5497775.html

    http://www.cnblogs.com/nianlei/p/5642315.html

    A wise man thinks all that he says, a fool says all that he thinks.
  • 相关阅读:
    hdu1251 字典树trie 模板题
    SPOJ 1479 +SPOJ 666 无向树最小点覆盖 ,第二题要方案数,树形dp
    POJ 2125 最小点权覆盖集(输出方案)
    dfs序+主席树 或者 树链剖分+主席树(没写) 或者 线段树套线段树 或者 线段树套splay 或者 线段树套树状数组 bzoj 4448
    dfs序+主席树 BZOJ 2588 当然树链剖分+主席树也可以?
    最小生成树的边的概念问题!!! 最小生成树的计数 bzoj 1016
    BZOJ 2083 vector的巧用+二分
    vector的哈希值 Codecraft-17 and Codeforces Round #391 (Div. 1 + Div. 2, combined) C
    codeforces Good bye 2016 E 线段树维护dp区间合并
    莫对 和分块 模板
  • 原文地址:https://www.cnblogs.com/BernieChen/p/5724702.html
Copyright © 2020-2023  润新知