python从零进阶之路——day2

列表list:增,删,查,改,切片,拷贝

1.切片

# -*- coding-utf8 -*-
# author:zingerman
name=['hu','zhao','wang','zhou']  
print(name[:2])           #默认从0开始
print(name[-3:-1])         #不能写成name[-1:-3]
print(name[-3:])            #默认从0开始
print(name[::2])            #步长为2,等效与name[0:-1:2]


2.增:

# -*- coding-utf8 -*-
# author:zingerman
name=['hu','zhao','wang','zhou']
name.append('sun')   #在列表的末尾添加元素
print(name)
name.insert(1,'qian')   #按索引插入元素
print(name)
name1=[1,2,3]
name.extend(name1)      #extend() 函数用于在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)
print(name)


3.删:

# -*- coding-utf8 -*-
# author:zingerman
name=['hu','zhao','wang','zhou','qian']
name.remove('zhao')       #remove() 函数用于移除列表中某个值,无返回值
print(name)
del name[1]                 #根据索引删除列表中的元素
print(name)
name.pop(1)                    #默认删除列表最后一个,或按索引删除
print(name)

 


4.查,拷贝:

# -*- coding-utf8 -*-
# author:zingerman
import copy
name=['hu','zhao',['qian','sun'],'wang','zhou']
print(name[2])
print(name[2][1])
print(name.index("hu"))
name2=copy.copy(name)    #另外两种copy的方式:1,name2=name[:]   2.name2=list(name)
print(name2)
#name[2]='b'
name[2][1]='1'      #1、copy.copy 浅拷贝 只拷贝父对象,不会拷贝对象的内部的子对象,拷贝的是内部子对象的地址,浅拷贝常用于创建联合账号
print(name)                #2、copy.deepcopy 深拷贝 拷贝对象及其子对象
print(name2)
 


5.其他:

# -*- coding-utf8 -*-
# author:zingerman
name=['hu','zhao','wang','zhou']
name.reverse()
print(name)
name.sort()
print(name)
name.clear()
print(name)

 元组:

元组其实跟列表差不多,也是存一组数,只不是它一旦创建,便不能再修改,所以又叫只读列表

语法

1
names  =  ( "alex" , "jack" , "eric" )

它只有2个方法,一个是count,一个是index,完毕。

购物车作业 :

#!/usr/bin/env python
# author:zingerman
product_list = [
    ('Iphone', 5800),
    ('Mac Pro', 9800),
    ('Bike', 800),
    ('Watch', 10600),
    ('Coffee', 31),
    ('Alex Python', 120),
]
shopping_list = []
salary = input('输入你的工资:')
if salary.isdigit():
    salary = int(salary)
    for item in product_list:
        print(product_list.index(item), item)
    coustom_choice = input('请输入商品标号;')
    # print(type(coustom_choice))
    while True:
        if coustom_choice.isdigit():
            coustom_choice = int(coustom_choice)
            if coustom_choice < len(product_list) and coustom_choice >= 0:
                if product_list[coustom_choice][1] <= salary:  # 买得起
                    shopping_list.append(product_list[coustom_choice])
                    salary -= product_list[coustom_choice][1]
                    print('你已经购买了%s,你的账户还剩%s元' % (shopping_list, salary))
                    coustom_choice = input('请继续输入商品标号;')
                else:
                    print('你的余额不足,还剩%s元' % (salary))
                    break
            else:
                coustom_choice = input('你输入编号太大,请重新输入')
        elif coustom_choice == 'q':
            break
        else:
            coustom_choice = input('你输入编号有误,请重新输入')
    print('谢谢惠顾,你已经购买了%s,你的账户还剩%s元' % (shopping_list, salary))

字符串操作:

name.capitalize()  首字母大写
name.casefold()   大写全部变小写
name.center(50,"-")  输出 '---------------------Alex Li----------------------'
name.count('lex') 统计 lex出现次数
name.encode()  将字符串编码成bytes格式
name.endswith("Li")  判断字符串是否以 Li结尾
 "Alex\tLi".expandtabs(10) 输出'Alex      Li', 将\t转换成多长的空格 
 name.find('A')  查找A,找到返回其索引, 找不到返回-1 

format :
    >>> msg = "my name is {}, and age is {}"
    >>> msg.format("alex",22)
    'my name is alex, and age is 22'
    >>> msg = "my name is {1}, and age is {0}"
    >>> msg.format("alex",22)
    'my name is 22, and age is alex'
    >>> msg = "my name is {name}, and age is {age}"
    >>> msg.format(age=22,name="ale")
    'my name is ale, and age is 22'
format_map
    >>> msg.format_map({'name':'alex','age':22})
    'my name is alex, and age is 22'


msg.index('a')  返回a所在字符串的索引
'9aA'.isalnum()   True

'9'.isdigit() 是否整数
name.isnumeric  
name.isprintable
name.isspace
name.istitle
name.isupper
 "|".join(['alex','jack','rain'])
'alex|jack|rain'


maketrans
    >>> intab = "aeiou"  #This is the string having actual characters. 
    >>> outtab = "12345" #This is the string having corresponding mapping character
    >>> trantab = str.maketrans(intab, outtab)
    >>> 
    >>> str = "this is string example....wow!!!"
    >>> str.translate(trantab)
    'th3s 3s str3ng 2x1mpl2....w4w!!!'

 msg.partition('is')   输出 ('my name ', 'is', ' {name}, and age is {age}') 

 >>> "alex li, chinese name is lijie".replace("li","LI",1)
     'alex LI, chinese name is lijie'

 msg.swapcase 大小写互换


 >>> msg.zfill(40)
'00000my name is {name}, and age is {age}'



>>> n4.ljust(40,"-")
'Hello 2orld-----------------------------'
>>> n4.rjust(40,"-")
'-----------------------------Hello 2orld'


>>> b="ddefdsdff_哈哈" 
>>> b.isidentifier() #检测一段字符串可否被当作标志符,即是否符合变量命名规则
True

字典:

1.增,改:

# -*- coding-utf8 -*-
# author:zingerman
info = {
    '01': "hu",
    '02': "li",
    '03': "zhao",
}
info[4]='sun'
info['02']='wang'
print(info)

2.删:

# -*- coding-utf8 -*-
# author:zingerman
info = {'01': "hu",'02': "li",'03': "zhao",'04':'wang'}
info.pop('01')                  #标准删除姿势
del info['02']                  #也是删除
info.popitem()                  #随机删除
print(info)

3.找;

# -*- coding-utf8 -*-
# author:zingerman
info = {'01': "hu",'02': "li",'03': "zhao",'04':'wang'}
print('01' in info)             #标准查找
print(info.get('01'))           #获取,可用于查找,如果找不到,返回none
print(info['01'])               #查找,但是找不到会报错,建议用上一种

4.字典嵌套:

av_catalog = {
    "欧美":{
        "www.youporn.com": ["很多免费的,世界最大的","质量一般"],
        "www.pornhub.com": ["很多免费的,也很大","质量比yourporn高点"],
        "letmedothistoyou.com": ["多是自拍,高质量图片很多","资源不多,更新慢"],
        "x-art.com":["质量很高,真的很高","全部收费,屌比请绕过"]
    },
    "日韩":{
        "tokyo-hot":["质量怎样不清楚,个人已经不喜欢日韩范了","听说是收费的"]
    },
    "大陆":{
        "1024":["全部免费,真好,好人一生平安","服务器在国外,慢"]
    }
}

av_catalog["大陆"]["1024"][1] += ",可以用爬虫爬下来"
print(av_catalog["大陆"]["1024"])
#ouput 
['全部免费,真好,好人一生平安', '服务器在国外,慢,可以用爬虫爬下来']

5.其他用法:

# author:zingerman
info = {'01': "hu",'02': "li",'03': "zhao",'04':'wang'}
print(info.values())
print(info.keys())
print(info.setdefault(4,'sun') ,'\t\t\t',info)

info1 ={'01': 'men',1:2}
info.update(info1)
print(info)                             #有则修改,无则添加

print("字典值 : %s" % info.items())              #items() 函数以列表返回可遍历的(键, 值) 元组数组
# 遍历字典列表
for key, values in info.items():
print(key, values)

猜你喜欢

转载自www.cnblogs.com/zingerman/p/9887719.html
今日推荐