python学习第三天

3年前 (2017-06-01) gtj python 0评论 已收录 506℃

python的sys模块

python的标准库路径:\Python\Python35\Lib

os模块

import os

#cmd_red=os.system("dir")  #执行命令不保存结果
#cmd_red = os.popen("dir") #执行命令保存结果
cmd_red = os.popen("dir").read() #执行命令保存结果,输出结果
print("---->",cmd_red)
结果:

2017/06/02  16:18    <DIR>          .
2017/06/02  16:18    <DIR>          ..
2017/06/02  13:11                 0 Readme
2017/06/02  16:18               322 ss_fangfa.py
               2 个文件            322 字节
               2 个目录 40,114,503,680 可用字节

import os
os.mkdir("new_dir")
创建目录,调用模块里的方法。
python也支持第三方模块,自己也可以自定义模块。
比如说可以写一个用户登录的功能,然后引用他。

mokuai.py
# -- coding: utf-8 -- #Author:随小风 ##自创功能模块 import getpass _username = 'alex' _password = '123' username = input("请输入用户名:") password = input("请输入密码:") if username == _username and password == _password: print("weblcome username %s login"% username) else: print("wrong username or password") print(username,password) login.py
import mokuai
结果: 请输入用户名: 可以把模块放在site-packages中就可以调用了。

三元运算

例子:

a,b,c =1,3,5
d=a  if a > b else  c
print  d 
5

二进制转化成字符串:decode
字符串转化成二进制:encode

# -- coding: utf-8 --
#Author:随小风
msg = "你好,你好"
print(msg)
print(msg.encode())#字符串转化为二进制
print(msg.encode(encoding="utf-8").decode(encoding="utf-8"))#再转化为字符串
结果:
你好,你好
b'\xe4\xbd\xa0\xe5\xa5\xbd\xef\xbc\x8c\xe4\xbd\xa0\xe5\xa5\xbd'
你好,你好

列表

例1:

names =  ["test","test2","test3"]
print(names[2],names[0])
结果:
test3 test

例2:取连续的值

names =  ["test","test2","test3"]
print(names[1:3]) #切片
print(names[-1]) ##从右向左取
print(names[-2:])
print(names[:3])
结果:
['test2', 'test3']
test3
['test2', 'test3']
['test', 'test2', 'test3']

例3:

列表中添加内容

names =  ["test","test2","test3"]
names.append("test4")  #追加到结尾。
print(names)
结果:
['test', 'test2', 'test3', 'test4']

插入到指定位置:

names =  ["test","test2","test3"]
names.insert(2,"hehhjjj")
print(names)
结果:
['test', 'hehhjjj', 'test2', 'test3'] ##插入到指定位置

改掉某个位置的值:

names =  ["test","test2","test3"]
names[2]="cccc" ##改掉第二个的值
names.insert(3,"hehhjjj")
names[2]="cccc" ##改掉第二个的值
print(names)
结果:
['test', 'hehh', 'cccc', 'hehhjjj', 'test3']

删除某一个值:

方法一:
names =  ["test","test2","test3"]
names.remove("test2")
print(names)
结果:
["test","test3"]
方法二:
del names[1]
结果:
 ["test","test3"]

方法三:
#names.pop() #无下标删除最后一位
names.pop(1)
结果:
 ["test","test3"]

查找

names =  ["test","test2","test3"]
print(names.index("test3"))
print(names[names.index("test3")]) #找到位置后打印出来
结果:
2
test3

查找列表中同一个字符串有几个

names =  ["test","test2","test3","test3"]
print(names.count("test3"))
结果:
2

清空列表

names =  ["test","test2","test3","test3"]
print(names)
names.clear()
print(names)
结果:
['test', 'test2', 'test3', 'test3']
[]

反转

names =  ["test","test2","test3","test3"]
print(names)
names.reverse()
print(names)
结果:
['test', 'test2', 'test3', 'test3']
['test3', 'test3', 'test2', 'test']

排序

names =  ["2test","#!test2","xtest3","Test3"]
print(names)
names.sort()
print(names)
结果:
['#!test2', '2test', 'Test3', 'xtest3']  ##先特殊字符,再数字,大写,小写。

列表的合并

names =  ["2test","#!test2","xtest3","Test3"]
print(names)
names2 = [1,2,3,4]
names.extend(names2)
print(names)
结果:
['2test', '#!test2', 'xtest3', 'Test3', 1, 2, 3, 4]

删除列表:

names =  ["2test","#!test2","xtest3","Test3"]
print(names)
names2 = [1,2,3,4]
names.extend(names2)
print(names)
#l names2
print(names2)
del names2
print(names2)
结果:
['2test', '#!test2', 'xtest3', 'Test3']
['2test', '#!test2', 'xtest3', 'Test3', 1, 2, 3, 4]
[1, 2, 3, 4]

复制一份列表

names =  ["2test","#!test2","xtest3","Test3"]
names2 = names.copy()
print(names2)
结果:
['2test', '#!test2', 'xtest3', 'Test3']

列表中子列表

列表的浅copy

适用场景:共同财产,不同的用户。

# -- coding: utf-8 --
#Author:随小风
names =  ["test","test2",["alex","jack"],"test3"]
print(names)
name2=names.copy() ##只copy第一层
print(name2)
names[1] ="测试2"
print(names)
names[2][0]="ALEX" #更改子列表的某一个值
print(names)
print(name2)

结果:

['test', 'test2', ['alex', 'jack'], 'test3']
['test', 'test2', ['alex', 'jack'], 'test3']
['test', '测试2', ['alex', 'jack'], 'test3']
['test', '测试2', ['ALEX', 'jack'], 'test3']
['test', 'test2', ['ALEX', 'jack'], 'test3']

列表的深复制


import copy
names =  ["test","test2",["alex","jack"],"test3"]
print(names)
name2 = copy.deepcopy(names)
print(name2)
names[1] ="测试2"
print(names)
names[2][0]="ALEXtt"
print(name2)

结果:

['test', 'test2', ['alex', 'jack'], 'test3']
['test', 'test2', ['alex', 'jack'], 'test3']
['test', '测试2', ['alex', 'jack'], 'test3']
['test', '测试2', ['ALEXtt', 'jack'], 'test3']
['test', 'test2', ['alex', 'jack'], 'test3']

列表的切片

names =  ["test","test2",["alex","jack"],"test3"]
print(names[0:-1:2]) ##范围第一位到最后一位,隔一个取一次值。
print(names[::2])

结果:

['test', ['ALEXtt', 'jack']]
['test', ['ALEXtt', 'jack']]

元祖

又称为只读列表,方法只有两个,count,index
元组使用小括号,列表使用方括号。
元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可。
如下实例:

tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";

创建空元组
tup1 = ();
元组中只包含一个元素时,需要在元素后面添加逗号
tup1 = (50,);

购物车的实例

下标引用的方法一

# -- coding: utf-8 --
#Author:随小风
_author_ ="suixiaofeng"


product_list = [
    ('Iphone',5800),
    ('Mac Pro', 9800),
    ('Watch', 10800),
    ('coffee', 31),
    ('python', 120),
]
salary = input("Input your salary:")
if salary.isdigit():
    salary =int(salary)
    while True:
          for item in product_list:
             print(product_list.index(item),item)
        

          break

结果:

Input your salary:1111
0 ('Iphone', 5800)
1 ('Mac Pro', 9800)
2 ('Watch', 10800)
3 ('coffee', 31)
4 ('python', 120)

下标引用的方法二

# -- coding: utf-8 --
#Author:随小风
_author_ ="suixiaofeng"
product_list = [
    ('Iphone',5800),
    ('Mac Pro', 9800),
    ('Watch', 10800),
    ('coffee', 31),
    ('python', 120),
]
salary = input("Input your salary:")
if salary.isdigit():
    salary =int(salary)
    while True:
      
        for  index,item  in enumerate(product_list):
            print(index,item)

        break

结果:

Input your salary:1111
0 ('Iphone', 5800)
1 ('Mac Pro', 9800)
2 ('Watch', 10800)
3 ('coffee', 31)
4 ('python', 120)

完整实例

# -- coding: utf-8 --
#Author:随小风
_author_ ="suixiaofeng"


product_list = [
    ('Iphone',5800),
    ('Mac Pro', 9800),
    ('Watch', 10800),
    ('coffee', 31),
    ('python', 120),
]
shopping_list=[]
salary = input("Input your salary:")
if salary.isdigit():
    salary =int(salary)
    while True:
       # for item in product_list:
            #print(product_list.index(item),item)
        for  index,item  in enumerate(product_list):
            print(index,item)
        user_choice = input("选择要买什么?>>>:")
        if user_choice.isdigit():
            user_choice = int(user_choice)
            if user_choice <  len(product_list) and user_choice >=0:
                p_item = product_list[user_choice]
                if p_item[1] <= salary:  #买得起
                     shopping_list.append(p_item)
                     salary -= p_item[1]
                     print("Added %s into shopping cart,your current balance is \033[31;1m%s\033[0m" %(p_item,salary))
                else:
                    print("\033[41;1m你的余额只剩下[%s]\033[0m" %salary)
            else:
                print("product code [%s] is not exist!"%user_choice)
        elif user_choice ==  'q':
              print("---------------shopping list -----------")
              for p in shopping_list:
                    print(p)
              print ("your current balance:",salary)
              exit()
        else:
            print("invalid option")

字符串

name = "this \tis test"

print(name.capitalize()) #首字母大写
print(name.count("t"))   #统计t有几个
print(name.center(50,"-"))#五十个字符,没有的,补充为-
print(name.endswith("st")) #判断结尾是以什么结尾
print(name.expandtabs(tabsize=30))#\t 加空格

结果:

This 	is test
3
------------------this 	is test-------------------
True
this                          is test

 -- coding: utf-8 --
#Author:随小风
names = " my  name is {name} and  i am {year} old"
print(names.format(name='suixiaofeng',year=25))



待续....

博主

这货来去如风,什么鬼都没留下!!!

相关推荐

嗨、骚年、快来消灭0回复。

×
订阅图标按钮
Less is more!!!