玩蛇(Python)笔记之基础Part2

玩蛇(Python)笔记之基础Part2

一.列表

1.列表 别的语言叫数组 python牛逼非要取个不一样的名字

 

1 age = 23
2 name = ["biubiubiu", "jiujiujiu", 22, age]
3 # namecopy = name
4 # namecopy.pop()
5 print(name)
6 # print(namecopy)
List

 

  2.列表取值 正常index 从零开始,,取倒数加负号 倒数第一就是[-1]

  3.列表切片 [0:2]取得是第一个和第二个,,也就是头取尾不取 取值永远按照列表顺序例如取倒数[-5:-1],,步长[::步长]默认步长是1!

  4.列表基本操作 追加list.append("") 插入到某个位置(如果指定倒数位置 将插入位置前面) list.insert(2,"") 删除list.remove("") del li[2]下标删除 切片删除(函数内无效)li=li[:] 弹出li.pop(index),,默认弹出最后一个

1 name = ["biubiubiu", "jiujiujiu", 22, age]
2 name.append("hahahaa")
3 name.insert(2, "uuuuuuu")
4 name.remove("biubiubiu")
5 del name[0:2]
6 print(name)
List base

  5.列表判断 in 数量li.count() 找索引li.index()只会返回找到的第一个元素位置 列表长度,,len(li)

1 if "hahahaa" in name:
2     num_of_sth = name.count("hahahaa")
3     posistion = name.index("hahahaa")
4     print("[%s] hahahaa in name.posistion is [%s]" % (num_of_sth, posistion))
List base

6.列表高端操作 拓展进一个新的列表 li.extend(li2) 反转列表li.reverse() 排序li.sort(),,python3数字和字符串排序会报错,,python2会按asc2码的顺序来排 拷贝li.copy() 枚举enumerate()

1 name2 = ["babababa", "hehehehe", "niuniuniu"]
2 name.extend(name2)
3 name.reverse()
4 # name.sort()
List base

7.列表注意!! 列表直接赋值是整个列表指引,,li=li2,,改变一个都会变 所以要用copy 但是copy为浅拷贝!!,,意思是被拷贝的列表里有嵌套列表,用copy后嵌套的列表依然为指引 如果要深拷贝,,请用copy库的deepcopy

1 name.append([1, 2, 3, 4, 5, 6])
2 nameShallowcopy = name.copy()
3 nameTruecopy = copy.deepcopy(name)
List copy

二.元组

1.元组truple 只读列表 元组不可更改 truple.count() truple.index()

1 r = (1, 2, 3, 4, 5)
truple

 

三.字符串

1.字符串操作 string.strip()默认脱空格换行tab,也可以指定 string.split(",")按指定符号拆分成列表,,string.join(列表)合并列表每个元素加入string ''in string判断有没有空格

1 username = 'year    '
2 username.strip()
3 usernames = 'uar,asdf,asdf,erg,erh'
4 username = usernames.split(',')
5 usernames = '|'.join(username)
6 print('' in usernames)
String

 

2.字符串操作2 string.capitalize()首字母大写 string.format()格式化字符串,,推荐使用 字符串切片同列表 指定长度填充居中string.center(40,'-') 查找指定字符串string.find('')返回索引 string.isdigit()等等判断是否为某个类型 string.endswith()startswith() string.upper().lower()

 1 usernames.capitalize()
 2 msgTamplte1 = "Hello, {name}, you are {age} years old!"
 3 msgTamplte2 = "Hello, {0}, you are {1} years old!"
 4 msg1 = msgTamplte1.format(name='year', age=23)
 5 msg2 = msgTamplte2.format('year', 23)
 6 
 7 usernames.center(50, '-')
 8 
 9 usernames.find('uar')
10 print(usernames.isdigit())
11 usernames.endswith('ddd')
12 usernames.startswith('asdf')
13 usernames.upper().lower()
String

 

3.关于字符串格式化后面会有专门的笔记......

四.数据操作

1.加减乘除不说 %号为取余数,,常用来判断奇偶数 **幂运算 //取整除,,返回商的整数部分

2.运算符 == != <> < > >= <=没什么好说的

3.赋值运算 = += -= *= /= %= **= //= 同样没什么好说的

4.逻辑运算 and or not 更没有什么好说的了

5.成员运算 in ,, not in 同样没什么好说的

6.身份运算 is ,, is not 判断两个标识符是不是引用自一个对象

7.位运算 & | ^异或 ~取反 << >> 二进制知识 计算机中能表示的最小单位和能存储的最小单位就是一个二进制位(bit) 8bit=byte(字节) 1024byte=1kbyte等等

 1 print(8 % 2)
 2 print(10 // 3)
 3 a = [1, 2, 3, 4]
 4 print(type(a) is list)
 5 a = 60  # 00111100
 6 b = 13  # 00001101
 7 c = 0
 8 
 9 c = a & b  # 12=00001100
10 c = a | b  # 61=00111101
11 c = a ^ b  # 49=00110001 相同为0不同为1
12 c = ~a  # 195=11000011 按位取反 结果为195-256
13 print(64 >> 1)  # 右移1位就是除2 右移2位就是除2再除2
14 print(64 << 1)  # 左移1位就是乘以2 位移动比直接用乘除运算快
+-*/

 

 

五.循环

1.while循环 while True: 少写死循环

 1 count = 0
 2 while True:
 3     if count > 50 and count < 60:
 4         print("hahahahah")
 5         count += 1
 6         continue
 7     count += 1
 8     if count == 100:
 9         print("100")
10         break
11 oke = 0
while

 

六.字典

1.字典 {}键值对 天然去重 字典是无序的

2.字典操作 添加,,直接写key=value 删除,,del .pop() 拷贝,,参考列表拷贝 取值一般用get()防报错 更新字典dic1.update(dic2),,存在相应的key就更新相应的值,不存在就会添加 转换为列表(键值对转换为元组,,元组组成列表)dic.items()一般不用 取所有value和key,,dic.values().keys()

3.字典操作2 判断字典有没有key,,用key in dic 加入空值键dic.setdefault(key,value),,如果存在该键就返回值否则就生成空值键,,也可以指定value 加入多个相同value的key,,dic.fromkeys([1,2,3,4,5],'ddddd')但是这是类方法和对象本身没有关系!!

4.字典操作3 随机删除dic.popitem()不要用 字典循环1 for key,value in dic.items()不好,,有一个dic到list的转换过程 循环2 for key in dic:

 1 id_db[124124124] = 'asdfasdf'
 2 del id_db[124124124]
 3 id_db[123123123].pop('jjj')
 4 id1 = id_db.get(123123123)
 5 id_db2 = {
 6     123123123: {
 7         'asdf': 'biubiubiu'
 8     },
 9     'hahaha': 'enenene'
10 }
11 id_db.update(id_db2)
12 id_db.items()
13 id_db.values()
14 id_db.keys()
15 
16 print(123123123 in id_db)
17 id_db.setdefault(125125125, 'hahaha')
18 id_db.fromkeys([1, 2, 3, 4, 5, 6], 'sssss')
19 
20 id_db.popitem()
21 for key in id_db:
22     print(id_db[key])
dic

 

 

七.举个栗子 购物车枚举

 

 1 # -*- coding:utf-8 -*-
 2 # Author:YEAR
 3 
 4 salary = input("Input your salary:")
 5 
 6 if salary.isdigit():
 7     salary = int(salary)
 8 else:
 9     exit("Invaild data type...")
10 
11 welcome_msg = 'Welcome to Alex Shopping mall'.center(50, '-')
12 product_list = [
13     ('iphone', 5999),
14     ('chuizi', 2999),
15     ('mac', 8000)
16 ]
17 print(welcome_msg)
18 
19 exit_flag = False
20 shop_car = []
21 while not exit_flag:
22     for item in (product_list):
23         index = item[0]
24         p_name = item[1][0]
25         p_price = item[1][1]
26         print(p_name, p_price)
27 
28     user_choic = input("[q=quit,c=check]What do you want to buy?:")
29     if user_choic.isdigit():  # 肯定是选商品
30         user_choic = int(user_choic)
31         if user_choic < len(product_list):
32             p_item = product_list[user_choic]
33             if p_item[1] <= salary:  # 买得起
34                 shop_car.append(p_item)
35                 salary -= p_item[1]
36                 print("Added [%s] into shop car, you current balance is [%s]" % (p_item, salary))
37             else:
38                 print("Your balance is [%s],cannot afford this ..." % salary)
39         else:
40             pass
41     else:
42         if user_choic == 'q' or user_choic == 'quit':
43             print("purchased product as below".center(40, '*'))
44             for item in shop_car:
45                 print(item)
46             print("Goodbye!".center(40, '*'))
47             print("Your balance is [%s]" % salary)
48             exit_flag = True
49         elif user_choic == 'c' or user_choic == 'check':
50             print("purchased product as below".center(40, '*'))
51             for item in shop_car:
52                 print(item)
53             #命令行上色 \033[31;1m[%s]\033[0m     32绿色 31红色 42背景绿色 41背景红色
54             print("Goodbye!".center(40, '*'))
shop

 

 

 

 

 

 

 

 

 

posted @ 2016-11-20 12:48  YEAR~  阅读(338)  评论(0编辑  收藏  举报