主干数据类型,用户注册登录种类

By admin in 4858.com on 2019年2月19日
  1. 列表和常见变量有哪些分歧
      列表是数据类型,普通变量是用来储存数据的
      可以把列表赋值给一般变量

一运算符

集合容器:列表 元组 列表和元组相互转换 字典 set

Jupyter最新版:https://www.cnblogs.com/dotnetcrazy/p/9155310.html

2.设有列表 a = [11, 22, 33], 怎样向列表中丰盛(增)新成分 44
  a.append(44)
  或者
  a.insert(3,44) #索引号为3

1算数运算符

列表:

用一对方括号[]意味着 列表中能够储存任何项目标数据

诚如景观下贰个列表存放的数据类型 都一样 那样方便对列表的操作


增:

list.append(value) 在列表底部添卢比素

value = list.insert(index) 根据索引向列表中插入成分

list.extend(list1) 向list追加list1中颇具的因素 也是多少个列表相连接的意味


删:

list.remove(value) 移除列表中有些成分

list.pop() 删除列表末尾成分

list.pop(index) 依照目录删除成分

del list[index] 按照目录删除成分


查:

value = list[index] 依照目录查找成分

list.count(value) 计算列表中某些成分出现次数

index = list[value] 依照值来搜寻对应的目录

len(list) 列表长度

max(list) 列表中成分最大值 仅限于列表中都是数字的事态

min(list) 列表元素最小值


改: list[index] = value

切片: list[x:y:l] x:从索引几始发(包罗) y:到目录几了却(不包括)
l:每一回切片的尺寸

普遍的二种情状

list = [1,2,3,4,5,6,7,8,9,0]

#从头切到位

print(list[::]) #[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

print(list[1:5:2]) #[2, 4]

print(list[0:5:2]) #[1, 3, 5]

print(list[::-1]) #[0, 9, 8, 7, 6, 5, 4, 3, 2, 1]

print(list[::-2]) #[0, 8, 6, 4, 2]

print(list[-2:1:-2])#[9, 7, 5, 3]

print(list[-2:1:2]) #[]若找不到则输出空列表

print(‘*’*30)


判断:

in 在则输出Ture 否则再次来到False

not in 不在则输出Ture 否则重回False


反转:

reserve()

list.reverse() 对原列表倒叙排列

list.sort() 按顺序排列

”’

#reverse = True 时倒序排列

list1 = [1,2,3,4,5,69,0,7,8,]

print(list1)

list1.sort()# list.sort()=list.sort(reserve = False)

print(list1)

list1.sort(reverse = True)#false 暗中同意正序 Ture 暗中同意倒序

print(list1)

”’


遍历: for in while enumerate

”’

list1 = [1,2,3,4,5,6,7,8,9,0]

print(‘****************1、for 变量名 in
list*******************’)

for a in list1:

 print(a)

print(‘****************2、for index in
range(list)*******************’)

for a in range(len(list1)):

print(‘index–>%s,value–>%s’%(a,list1[a]))

print(‘****************3、while index <
len(list)*******************’)

a = 0

while a < len(list1):

print(‘index–>%s,value–>%s’%(a,list1[a]))

a+=1

print(‘****************4、for index,obj in
enumerate(list)*******************’)

for a,obj in enumerate(list1):

print(‘index–>%s,value–>%s’%(a,list1[a]))

”’


在线演示: style=”color: #008000;”>http://nbviewer.jupyter.org/github/lotapp/BaseCode/blob/master/python/notebook/1.POP/3.list\_tuple\_dict

更新: style=”color: #ff0000;”>新增Python可变Tuple、List切片、Set的扩展:https://www.cnblogs.com/dotnetcrazy/p/9155310.html\#extend 

明天说说List和Tuple以及Dict。POP部分还有局地如Func、IO(也可以放OOP部分说)然后就说说面向对象吧。

先吐槽一下:Python面向对象真心要求正式,不然太简单走火入魔了 -_-!!!
汗,下次加以。。。

比较写作真的比单写累很多,希望大家多捧捧场 ^_^

3.对列表排序
  a = [11,22,33,2]
  b = sorted(a) #始建了三个新的列表 ,a.sort()修改a列表
  print(b) # [2, 11, 22, 33, 44]

4858.com 1

元组:

tuple用一对小括号()表示

元组和列表相似 可是元组是不足更改的

有询问,判断的操作

max(tup) min(tup) value = tup[index] len(tup) in not in

删除的话是删除全体列表

和列表一样也足以动用三种格局遍历

列表和元组相互转换:

list = list(tup)

tup = tuple(list)

”’

list1 = [5,6,7]

tup = tuple(list1)

print(tup)

tup = (1,2,3)

list1=list(tup)

print(list1)

”’


进入增添:https://www.cnblogs.com/dotnetcrazy/p/9155310.html\#ext

  b = a.sort()
  print(b) # None

2.相比运算符

字典:

用对花括号表示{key:value}

字典里面成分都以键值对的款型存在 key必须是绝无仅有的 value可以是其余类型


增(改):

map(‘key’) = value 若字典中一向不应该键则添加 若有则更新此键对应的值


删:

map.pop(key) 根据键删除成分 并将此因素重回

map.popitem() 随机删除贰个键值对

del map[key] 依照键删除成分

map.clear() 清空字典


查:

value = map[key] 依据键查询值 若无此键报错

value = map.get(key,[默认值])
若是key不设有,可以重临None,或然本人内定的value

len(map) 字典中键值对的个数

str(map) 输出字典可打印的字符串表示

map.keys() 输出全数键

map.values() 输出全体值

map.items() 输出全部键值对


判断: in not in

遍历:for循环遍历的二种方法

”’

map1 =  {‘a’:’a’,’b’:’b’,’c’:’c’,’d’:’d’}

for a in map1.keys():

print(‘key–>%s,value–>%s’%(a,map1[a]))

print(‘***********************************’)

for a in map1:

print(‘key–>%s,value–>%s’%(a,map1[a]))

print(‘***********************************’)

for k,v in map1.items():

print(‘key–>%s,value–>%s’%(k,v))

”’


其它操作:

map2 = map1.copy() 再次回到一个新的字典,内容一律,地址差别

dict.update(dict2) 把字典dict2的键值对创新到dict里

和list比较,dict有以下几天性状:

招来速度极快,不会趁机key的增加而变慢;

亟待占用多量的内存,内存浪费多。

而list:

探寻和插入的时辰随着成分的增多而增加;

占据空间小,浪费内存很少。

之所以,dict是用空间来换取时间的一种艺术。

步入正题:

  print(a) # [2, 11, 22, 33, 44]

4858.com 2

set:

set = {值1,值2,…..值}

set是无序的 成分不可重复的集合 可以用来过滤重复成分

增:

set.add(value) 向set中添欧成分

set.update(value) 将3个可迭代的内容,一HUAWEI入set中


删:

set.pop() 删除任意三个值

set.discard(value) 删除钦点元素 若无此因素也不报错

set.remove(value) 删除内定成分 若无此因素报错

set.clear() 清空set集合


其他:

| 并集

& 交集

intersection 交集函数 print(set.union(set1))

– 差集

difference 差集

in 判断

union 联合

issubset 子集

issuperset 父集


多维:

多维列表,元组

就是列表里套列表 那里以列表为例子

”’

list1 = [[1,2],[1,2,3],[1,2,3,4,],[1,2,3,4,5]]


#遍历此列表

x = 0

#外层循环遍历行

while x < len(list1):

y = 0

#内层循环遍历列

while y < len(list1[x]):

print(‘x–>%s,y–>%s,xy–>%s’%(x,y,list1[x][y]))

y+=1

x+=1

主干数据类型,用户注册登录种类。”’


4.存在字典 info = {‘name’:’李四’}, 删除成分 name
  del info[“name”]
  或者
  info.pop(“name”)

3.赋值运算符

传递:

可变类型:列表 字典 set

多个变量引用同一个成分时 地址值是一模一样的,

当1个变量值暴发变化另一个变量值 也会发生变化

不可变类型:int float str bool None 元组

两个变量引用贰个值时,地址值时一样的修改多个变量值,

不会影响此外二个变量值

”’

#不足变类型

a = 1

b = a

print(a)

print(id(a))

print(b)

print(id(b))

print(‘**********************’)

a = 2

print(a)

print(id(a))

print(b)

print(id(b))

print(‘**********************’)

#可变类型

set = {1,2,3,4,5,56}

set1 = set

print(set)

print(id(set))

print(set1)

print(id(set1))

print(‘**********************’)

set.pop()

print(set)

print(id(set))

print(set1)

print(id(set1))

 1.列表连锁:

5.字典和列表的例外以及使用字典的目标
  字典是以键值对的花样储存数据的,字典是无序的,通过键获取到对应值
  列表是板上钉钉的,通过下标获取到值
  使用字典可以储存一些有标识性的数据,可以为数据起2个一定的名字。

4858.com 3

style=”color: #ff6600;”>Python定义3个列表(列表纵然可以存差别档次,一般大家把相同类其余值存列表里面,不一样种类存字典里(key,value))

info_list=[] #空列表

style=”color: #ff6600;”>infos_list=[“C#”,”JavaScript”]

遍历和事先一样,for 大概 while
都足以(for伸张:)

4858.com 4

NetCore style=”color: #ff6600;”>var infos_list = new List<object>() {
“C#”, “JavaScript” };

遍历可以用foreach,for,while

4858.com 5


Python列表的丰硕

# 最终追加 infos_list. style=”color: #ff6600;”>append(“Java”)

#  style=”color: #ff6600;”>添加贰个列表 infos_list. style=”color: #ff6600;”>extend(infos_list2)

# style=”color: #ff6600;”>内定地点插入 infos_list. style=”color: #ff6600;”>insert(0,”Python”) 

# 插入列表:infos_list style=”color: #ff6600;”>.insert(0,temp_list) 

 看前边的 style=”color: #339966;”>列表嵌套,是因而下标形式获取,eg:
infos_list[0][1]

4858.com 6

style=”color: #ff6600;”>Python在内定地点插入列表是确实插入多个列表进去,C#是把其中的因素挨个插入进去

4858.com 7

style=”color: #ff6600;”>NetCore:Add,AddRange,Insert,InsertRange
(和Python插入列表有个别分裂)

4858.com 8


Python列表删除种类

infos_list.pop()
#删除最终多个

infos_list.pop(0)
#去除内定索引,不设有就报错

infos_list. style=”color: #ff6600;”>remove(“张三”)  style=”background-color: initial;”>#
remove(“”)删除钦点成分 style=”background-color: initial;”>,不设有就报错

4858.com 9

style=”color: #ff6600;”>del infos_list[1] #除去钦赐下标成分,不设有就报错

del
infos_list
 #删除集合(集合再拜访就不存在了)不相同于C#给集合赋null

4858.com 10

再过三次4858.com 11

style=”color: #ff6600;”>NetCore移除钦赐索引:infos_list. style=”color: #ff6600;”>RemoveAt(1); 移除指定值
infos_list. style=”color: #ff6600;”>Remove(item); 清空列表: infos_list. style=”color: #ff6600;”>Clear();

4858.com 12


style=”color: #ff6600;”>Python修改:(只好通过索引修改)

infos_list2[1]=”PHP”
#惟有下标修改一种格局, style=”background-color: initial;”>不存在则卓殊

# 想按值修改须求先查下标再修改 eg:

infos_list2.index(“张三”)

infos_list2[0]=”GO”

# infos_list2.index(“dnt”)#不存在则不行

style=”color: #000000;”>4858.com 13

# 知识面拓展:

# 为何python中不指出在for循环中修改列表?

#
由于在遍历的进度中,删除了其中一个要素,导致前边的成分全部前移,导致有个因素成了漏网之鱼。

#
同样的,在遍历进程中,使用插入操作,也会促成类似的一无可取。那相当于难题里说的不能够“跟踪”成分。

# 若是采取while,则足以在面对那样意况的时候灵活应对。

NetCore:基本上和Python一样

4858.com 14


style=”color: #ff6600;”>Python查询连串:in, not in,
index, count

if “张三” in names_list:

  names_list.remove(“张三”)

if “大舅子” not in
names_list:

  names_list.append(“大舅子”)

names_list.index(“王二麻子”)

names_list.count(“逆天”)

style=”color: #000000;”>4858.com 15

NetCore: style=”color: #008000;”>IndexOf , style=”color: #008000;”>Count

4858.com 16

查找用 style=”color: #008000;”>Contains,其余的先看看,前边会讲

4858.com 17


Python排序 style=”background-color: initial;”> 

num_list.reverse()  style=”background-color: initial;”># 倒序

num_list.sort()  style=”background-color: initial;”># 从小到大排序

num_list. style=”color: #ff6600;”>sort(reverse=True)  style=”background-color: initial;”># 从大到小

4858.com 18

style=”color: #ff6600;”>列表嵌套,获取用下标的点子: style=”color: #ff6600;”>num_list[5][1]

4858.com 19

NetCorevar num_list2 =
new List<object>() { 33, 44, 22, style=”color: #008000;”>new List<object>(){11,55,77} };

不只怕像python那样下标操作,可以定义多维数组来支撑 num_list2[i][j]
(PS,其实这一个嵌套不太用,以后都是列表里面套Dict,类似与Json)

4858.com 20

列表增泰铢素格局:
list.append(s),list.extend(list2),list.insert(index,s),

4.逻辑运算符

2.Tuple 元组

4858.com 214858.com 22

4858.com 23

这一次先说 style=”color: #00八千;”>NetCore吧:(逆天ValueTuple用的可比多,上边案例就是用的那几个)

元组系:

值元组:

 

style=”font-size: 15px;”>C#中元组紧如若便宜程序员,不用自然可以。 style=”background-color: initial;”>比如:当你回去三个值是还是不是还用ref out
只怕重返一个list之类的? style=”background-color: initial;”> 这个都必要先定义,相比麻烦.元祖在这么些处境用的相比较多。 style=”background-color: initial;”>先说说基本采取:

 

style=”background-color: initial;”>初始化: style=”background-color: initial;”>var
test_tuple = (“萌萌哒”, 1, 3, 5, “加息”, “加息”);
//那种措施就是valueTuple了(看vscode监视音讯)

4858.com 24

亟需说下的是,取值只好通过itemxxx来取了,然后就是 style=”color: #ff6600;”>valueTuple的值是能够修改的

4858.com 25

忽略上边说的(一般不会用的),直接进应用场景:

4858.com 26

就说到这了,代码部分附录是部分

 

style=”color: #ff6600;”>Python:用法基本上和列表大致( style=”color: #ff0000;”>下标和前面说的用法一样,比如test_tuples[-1]
最终三个要素)

概念:一个因素:test_tuple1= style=”color: #ff6600;”>(1,)

 

test_tuple=(“萌萌哒”,1,3,5,”加息”,”加息”)

test_tuple. style=”color: #ff6600;”>count(“加息”)

test_tuple. style=”color: #ff6600;”>index(“萌萌哒”)  style=”background-color: initial;”>#没有find方法

test_tuple.index(“加息”, 1, 4) #从一定岗位查找, style=”background-color: initial;”>左闭右开区间==>[1,4)

4858.com 27

来说说拆包相关的,C#的地方说了,那边来个案例即可:

a=(1,2)

b=a #把a的引用给b

c,d=a
#不是把a分别赋值给c和d,等价于: style=”color: #ff6600;”>c=a[0] d=a[1]

4858.com 28

来个增加吧(多维元组)

some_tuples=[(2,”萌萌哒”),(4,3)]

some_tuples[0]

some_tuples[0][1]

4858.com 29

1 a = [11,22,33,2]
2 b= [22,44]
3 str = '2'
4 a.extend(str)  # [11, 22, 33, 2, '2']
5 print(a)
6 a.extend(b)  # [11, 22, 33, 2, '2', 22, 44]
7 print(a)

 

3.Dict系列

View Code

二.中坚数据类型

Python遍历相关

#每两次约等于取三个元组,那可以用事先讲的事例来简化了:c,d=a
#等价于:c=a[0] d=a[1]

for k,v in
infos_dict.items():

  print(“Key:%s,Value:%s”%(k,v))

4858.com 30 

NetCore:方式和Python差不多

foreach (KeyValuePair<string,
object> kv in infos_dict)

{

  Console.WriteLine($”Key:{ style=”color: #ff6600;”>kv.Key},Value:{ style=”color: #ff6600;”>kv.Value}”);

}

4858.com 31 


Python style=”background-color: initial;”>增删改连串:

增加、修改 style=”color: #ff6600;”>infos_dict[“wechat”]=”dotnetcrazy style=”background-color: initial;”> style=”color: #ff6600;”>” #有就修改,没就添加

删去种类

# 删除

del
infos_dict[“name”] #不设有就报错

#清空字典内容

infos_dict.clear()

# 删除字典

del infos_dict

4858.com 32

NetCore

添加:infos_dict.Add(“wechat”, “lll”);  infos_dict[“wechat1”] =
“lll”;

修改

infos_dict[“wechat”] = “dotnetcrazy”;

 

删除

style=”background-color: initial;”>infos_dict.Remove(“dog”);
// style=”color: #ff6600;”>不存在不报错   style=”background-color: initial;”>infos_dict.Clear(); // style=”color: #ff6600;”>列表内容清空

4858.com 33 


Python查询种类 style=”background-color: initial;”>: style=”background-color: #ffff00;”>推荐 style=”background-color: initial;”>:infos_dict. style=”color: #ff6600;”>get(“mmd”)  style=”background-color: initial;”>#查不到不会那些

4858.com 34


  style=”color: #339966;”>NetCoreinfos_dict[“name”]
可以通过  style=”color: #ff6600;”>ContainsKey(key) 幸免极度。看值就
ContainsValue(value)

4858.com 35

 

1.数字

扩展:

字典:dict[key] = value,dict.update(dict2) ,

数字 age = 123

1.多维元组:

some_tuples=[(2,”萌萌哒”),(4,3)]

some_tuples[0]

some_tuples[0][1]

style=”background-color: initial;”>4858.com 36


2.运算符扩充:(+,*,in,not in)

# 运算符增加:

test_str=”www.baidu.com”

test_list=[1,”d”,5]

test_dict={“name”:”dnt”,”wechat”:”xxx”}

test_list1=[2,4,”n”,”t”,3]

# + 合并 (不扶助字典)

print(test_str+test_str)

print(test_list+test_list1)

# * 复制 (不帮助字典)

print(test_str*2)

print(test_list*2)

4858.com 37

# in 是不是存在(字典是查key)

print(“d” in test_str) #True

print(“d” in test_list) #True

print(“d” in test_dict) #False

print(“name” in test_dict) #True

 

# not in 是不是不存在(字典是查key)

print(“z” not in test_str) #True

print(“z” not in test_list) #True

print(“z” not in test_dict) #True

print(“name” not in test_dict) #False

4858.com 38


style=”background-color: initial;”>3.内置函数扩大:(len,max,min,del)

len(),那几个就隐瞒了,用的太多了

4858.com 39

max(),求最大值,dict的最大值是相比较的key

4858.com 40

其一注意一种情景(当然了,你依据事先说的标准,list里面放同一种类型就不会出错了)

4858.com 41

min(),这个和max一样用

4858.com 42

del() or del xxx 删完就木有了

4858.com 43

 

#可以先忽略cmp(item1,
item2) 
  相比较七个值 # style=”color: #ff6600;”>是Python2其间有些 cmp(1,2) ==>
-1
#cmp在可比字典数据时,先相比较键,再相比较值

set集合(hash存储):set.add(s),set.update(iterable)

4858.com 444858.com 45

知识扩充

4858.com 464858.com 47

  1 复制代码
  2 class int(object):
  3     """
  4     int(x=0) -> int or long
  5     int(x, base=10) -> int or long
  6     
  7     Convert a number or string to an integer, or return 0 if no arguments
  8     are given.  If x is floating point, the conversion truncates towards zero.
  9     If x is outside the integer range, the function returns a long instead.
 10     
 11     If x is not a number or if base is given, then x must be a string or
 12     Unicode object representing an integer literal in the given base.  The
 13     literal can be preceded by '+' or '-' and be surrounded by whitespace.
 14     The base defaults to 10.  Valid bases are 0 and 2-36.  Base 0 means to
 15     interpret the base from the string as an integer literal.
 16     >>> int('0b100', base=0)
 17     4
 18     """
 19     def bit_length(self): 
 20         """ 返回表示该数字的时占用的最少位数 """
 21         """
 22         int.bit_length() -> int
 23         
 24         Number of bits necessary to represent self in binary.
 25         >>> bin(37)
 26         '0b100101'
 27         >>> (37).bit_length()
 28         6
 29         """
 30         return 0
 31 
 32     def conjugate(self, *args, **kwargs): # real signature unknown
 33         """ 返回该复数的共轭复数 """
 34         """ Returns self, the complex conjugate of any int. """
 35         pass
 36 
 37     def __abs__(self):
 38         """ 返回绝对值 """
 39         """ x.__abs__() <==> abs(x) """
 40         pass
 41 
 42     def __add__(self, y):
 43         """ x.__add__(y) <==> x+y """
 44         pass
 45 
 46     def __and__(self, y):
 47         """ x.__and__(y) <==> x&y """
 48         pass
 49 
 50     def __cmp__(self, y): 
 51         """ 比较两个数大小 """
 52         """ x.__cmp__(y) <==> cmp(x,y) """
 53         pass
 54 
 55     def __coerce__(self, y):
 56         """ 强制生成一个元组 """ 
 57         """ x.__coerce__(y) <==> coerce(x, y) """
 58         pass
 59 
 60     def __divmod__(self, y): 
 61         """ 相除,得到商和余数组成的元组 """ 
 62         """ x.__divmod__(y) <==> divmod(x, y) """
 63         pass
 64 
 65     def __div__(self, y): 
 66         """ x.__div__(y) <==> x/y """
 67         pass
 68 
 69     def __float__(self): 
 70         """ 转换为浮点类型 """ 
 71         """ x.__float__() <==> float(x) """
 72         pass
 73 
 74     def __floordiv__(self, y): 
 75         """ x.__floordiv__(y) <==> x//y """
 76         pass
 77 
 78     def __format__(self, *args, **kwargs): # real signature unknown
 79         pass
 80 
 81     def __getattribute__(self, name): 
 82         """ x.__getattribute__('name') <==> x.name """
 83         pass
 84 
 85     def __getnewargs__(self, *args, **kwargs): # real signature unknown
 86         """ 内部调用 __new__方法或创建对象时传入参数使用 """ 
 87         pass
 88 
 89     def __hash__(self): 
 90         """如果对象object为哈希表类型,返回对象object的哈希值。哈希值为整数。在字典查找中,哈希值用于快速比较字典的键。两个数值如果相等,则哈希值也相等。"""
 91         """ x.__hash__() <==> hash(x) """
 92         pass
 93 
 94     def __hex__(self): 
 95         """ 返回当前数的 十六进制 表示 """ 
 96         """ x.__hex__() <==> hex(x) """
 97         pass
 98 
 99     def __index__(self): 
100         """ 用于切片,数字无意义 """
101         """ x[y:z] <==> x[y.__index__():z.__index__()] """
102         pass
103 
104     def __init__(self, x, base=10): # known special case of int.__init__
105         """ 构造方法,执行 x = 123 或 x = int(10) 时,自动调用,暂时忽略 """ 
106         """
107         int(x=0) -> int or long
108         int(x, base=10) -> int or long
109         
110         Convert a number or string to an integer, or return 0 if no arguments
111         are given.  If x is floating point, the conversion truncates towards zero.
112         If x is outside the integer range, the function returns a long instead.
113         
114         If x is not a number or if base is given, then x must be a string or
115         Unicode object representing an integer literal in the given base.  The
116         literal can be preceded by '+' or '-' and be surrounded by whitespace.
117         The base defaults to 10.  Valid bases are 0 and 2-36.  Base 0 means to
118         interpret the base from the string as an integer literal.
119         >>> int('0b100', base=0)
120         4
121         # (copied from class doc)
122         """
123         pass
124 
125     def __int__(self): 
126         """ 转换为整数 """ 
127         """ x.__int__() <==> int(x) """
128         pass
129 
130     def __invert__(self): 
131         """ x.__invert__() <==> ~x """
132         pass
133 
134     def __long__(self): 
135         """ 转换为长整数 """ 
136         """ x.__long__() <==> long(x) """
137         pass
138 
139     def __lshift__(self, y): 
140         """ x.__lshift__(y) <==> x<<y """
141         pass
142 
143     def __mod__(self, y): 
144         """ x.__mod__(y) <==> x%y """
145         pass
146 
147     def __mul__(self, y): 
148         """ x.__mul__(y) <==> x*y """
149         pass
150 
151     def __neg__(self): 
152         """ x.__neg__() <==> -x """
153         pass
154 
155     @staticmethod # known case of __new__
156     def __new__(S, *more): 
157         """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
158         pass
159 
160     def __nonzero__(self): 
161         """ x.__nonzero__() <==> x != 0 """
162         pass
163 
164     def __oct__(self): 
165         """ 返回改值的 八进制 表示 """ 
166         """ x.__oct__() <==> oct(x) """
167         pass
168 
169     def __or__(self, y): 
170         """ x.__or__(y) <==> x|y """
171         pass
172 
173     def __pos__(self): 
174         """ x.__pos__() <==> +x """
175         pass
176 
177     def __pow__(self, y, z=None): 
178         """ 幂,次方 """ 
179         """ x.__pow__(y[, z]) <==> pow(x, y[, z]) """
180         pass
181 
182     def __radd__(self, y): 
183         """ x.__radd__(y) <==> y+x """
184         pass
185 
186     def __rand__(self, y): 
187         """ x.__rand__(y) <==> y&x """
188         pass
189 
190     def __rdivmod__(self, y): 
191         """ x.__rdivmod__(y) <==> divmod(y, x) """
192         pass
193 
194     def __rdiv__(self, y): 
195         """ x.__rdiv__(y) <==> y/x """
196         pass
197 
198     def __repr__(self): 
199         """转化为解释器可读取的形式 """
200         """ x.__repr__() <==> repr(x) """
201         pass
202 
203     def __str__(self): 
204         """转换为人阅读的形式,如果没有适于人阅读的解释形式的话,则返回解释器课阅读的形式"""
205         """ x.__str__() <==> str(x) """
206         pass
207 
208     def __rfloordiv__(self, y): 
209         """ x.__rfloordiv__(y) <==> y//x """
210         pass
211 
212     def __rlshift__(self, y): 
213         """ x.__rlshift__(y) <==> y<<x """
214         pass
215 
216     def __rmod__(self, y): 
217         """ x.__rmod__(y) <==> y%x """
218         pass
219 
220     def __rmul__(self, y): 
221         """ x.__rmul__(y) <==> y*x """
222         pass
223 
224     def __ror__(self, y): 
225         """ x.__ror__(y) <==> y|x """
226         pass
227 
228     def __rpow__(self, x, z=None): 
229         """ y.__rpow__(x[, z]) <==> pow(x, y[, z]) """
230         pass
231 
232     def __rrshift__(self, y): 
233         """ x.__rrshift__(y) <==> y>>x """
234         pass
235 
236     def __rshift__(self, y): 
237         """ x.__rshift__(y) <==> x>>y """
238         pass
239 
240     def __rsub__(self, y): 
241         """ x.__rsub__(y) <==> y-x """
242         pass
243 
244     def __rtruediv__(self, y): 
245         """ x.__rtruediv__(y) <==> y/x """
246         pass
247 
248     def __rxor__(self, y): 
249         """ x.__rxor__(y) <==> y^x """
250         pass
251 
252     def __sub__(self, y): 
253         """ x.__sub__(y) <==> x-y """
254         pass
255 
256     def __truediv__(self, y): 
257         """ x.__truediv__(y) <==> x/y """
258         pass
259 
260     def __trunc__(self, *args, **kwargs): 
261         """ 返回数值被截取为整形的值,在整形中无意义 """
262         pass
263 
264     def __xor__(self, y): 
265         """ x.__xor__(y) <==> x^y """
266         pass
267 
268     denominator = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
269     """ 分母 = 1 """
270     """the denominator of a rational number in lowest terms"""
271 
272     imag = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
273     """ 虚数,无意义 """
274     """the imaginary part of a complex number"""
275 
276     numerator = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
277     """ 分子 = 数字大小 """
278     """the numerator of a rational number in lowest terms"""
279 
280     real = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
281     """ 实属,无意义 """
282     """the real part of a complex number"""

  style=”color: #ff0000;”>可变的元组(元组在概念的时候就无法变了,然则可以通过类似这种艺术来改变)

4858.com 48

List切片

4858.com 49

4858.com 50


Set集合扩充:

4858.com 514858.com 524858.com 53


更新:(漏了2个去除的法门):

4858.com 54

概念再补偿下

# dict内部存放的次第和key放入的顺序是不曾关系的
#
dict的key必须是不可变对象(dict依据key进行hash算法,来总括value的仓储地点
# 如若老是总结同一的key得出的结果不一致,那dict内部就完全混乱了)

用一张图驾驭一下:(测试结果: style=”color: #ff6600;”>元组是足以当作Key的 -_-!

4858.com 55

1 set1 = {10,3.13,20,"hello"}
2 set2 = {10,18}
3 set1.update(set2)  # 10未被添加,18被加入
4 print(set1)
5 
6 list = [1,[2,3]]
7 set1.update(list)  # TypeError: unhashable type: 'list'

int

附录Code

View Code

indetationError 缩进错误

Python:

Python List:

4858.com 564858.com 57

# 定义一个列表,列表虽然可以存不同类型,一般我们把相同类型的值存列表里面,不同类型存字典里(key,value)
infos_list=["C#","JavaScript"]#[]

# ###########################################################
# # 遍历 for while
# for item in infos_list:
#     print(item)

# i=0
# while i<len(infos_list):
#     print(infos_list[i])
#     i+=1
# ###########################################################
# # 增加
# # 末尾追加
# infos_list.append("Java")
# print(infos_list)

# # 指定位置插入
# infos_list.insert(0,"Python")
# print(infos_list)

# temp_list=["test1","test2"]
# infos_list.insert(0,temp_list)
# print(infos_list)

# # 添加一个列表
# infos_list2=["张三",21]#python里面的列表类似于List<object>
# infos_list.extend(infos_list2)
# print(infos_list)

# # help(infos_list.extend)#可以查看etend方法描述
# ###########################################################
# # 删除
# # pop()删除最后一个元素,返回删掉的元素
# # pop(index) 删除指定下标元素
# print(infos_list.pop())
# print(infos_list)
# print(infos_list.pop(0))
# # print(infos_list.pop(10)) #不存在就报错
# print(infos_list)

# # remove("")删除指定元素
# infos_list.remove("张三")
# # infos_list.remove("dnt") #不存在就报错
# print(infos_list)

# # del xxx[index] 删除指定下标元素
# del infos_list[1]
# print(infos_list)
# # del infos_list[10] #不存在就报错

# # del infos_list #删除集合(集合再访问就不存在了)
# ###########################################################
# # 修改 xxx[index]=xx
# # 注意:一般不推荐在for循环里面修改
# print(infos_list2)
# infos_list2[1]="PHP" #只有下标修改一种方式
# # infos_list2[3]="GO" #不存在则异常
# print(infos_list2)

# # 想按值修改需要先查下标再修改
# infos_list2.index("张三")
# infos_list2[0]="GO"
# print(infos_list2)
# # infos_list2.index("dnt")#不存在则异常

# # 知识面拓展: https://www.zhihu.com/question/49098374
# # 为什么python中不建议在for循环中修改列表?
# # 由于在遍历的过程中,删除了其中一个元素,导致后面的元素整体前移,导致有个元素成了漏网之鱼。
# # 同样的,在遍历过程中,使用插入操作,也会导致类似的错误。这也就是问题里说的无法“跟踪”元素。
# # 如果使用while,则可以在面对这样情况的时候灵活应对。

###########################################################
# # 查询 in, not in, index, count
# # # for扩展:https://www.cnblogs.com/dotnetcrazy/p/9102030.html#forelse

# names_list=["张三","李四","王二麻子"]

# # #张三在列表中执行操作
# if "张三" in names_list:
#     names_list.remove("张三")
# print(names_list)

# # #查看"大舅子"不在列表中执行操作
# if "大舅子" not in names_list:
#     names_list.append("大舅子")
# print(names_list)

# # #查询王二麻子的索引
# print(names_list.index("王二麻子"))

# print(names_list.count("大舅子")) 
# print(names_list.count("逆天")) 
###########################################################
# # 排序(sort, reverse 逆置)
# num_list=[1,3,5,88,7]

# #倒序
# num_list.reverse()
# print(num_list)

# # 从小到大排序
# num_list.sort()
# print(num_list)

# # 从大到小
# num_list.sort(reverse=True)
# print(num_list)
# # ###########################################################

# # #列表嵌套(列表也是可以嵌套的)
# num_list2=[33,44,22]
# num_list.append(num_list2)
# print(num_list)
# # for item in num_list:
# #     print(item,end="")

# print(num_list[5])
# print(num_list[5][1])
# # ###########################################################

# # # 引入Null==>None
# # a=[1,2,3,4]
# # b=[5,6]
# # a=a.append(b)#a.append(b)没有返回值
# # print(a)#None

View Code

Python Tuple:

4858.com 584858.com 59

# 只能查询,其他操作和列表差不多(不可变)
test_tuple=("萌萌哒",1,3,5,"加息","加息")

# count index
print(test_tuple.count("加息"))
print(test_tuple.index("萌萌哒"))#没有find方法
# 注意是左闭右开区间==>[1,4)
# print(test_tuple.index("加息", 1, 4))#查不到报错:ValueError: tuple.index(x): x not in tuple

#下标取
print(test_tuple[0])

# 遍历
for item in test_tuple:
    print(item)

i=0
while i

# 扩展:
test_tuple1=(1,) #(1)就不是元祖了
test_tuple2=(2)
print(type(test_tuple1))
print(type(test_tuple2))

# # ==============================================
# 扩展:(后面讲字典遍历的时候会再提一下的)
a=(1,2)
b=a#把a的引用给b
#a里面两个值,直接给左边两个变量赋值了(有点像拆包了)
c,d=a #不是把a分别赋值给c和d,等价于:c=a[0] d=a[1]

print(a)
print(b)
print(c)
print(d)

View Code

Python Dict:

4858.com 604858.com 61

infos_dict={"name":"dnt","web":"dkill.net"}

# # 遍历
# for item in infos_dict.keys():
#     print(item)

# #注意,如果你直接对infos遍历,其实只是遍历keys
# for item in infos_dict:
#     print(item)

# for item in infos_dict.values():
#     print(item)

# for item in infos_dict.items():
#     print("Key:%s,Value:%s"%(item[0],item[1]))
# #每一次相当于取一个元组,那可以用之前讲的例子来简化了:c,d=a #等价于:c=a[0] d=a[1]
# for k,v in infos_dict.items():
#     print("Key:%s,Value:%s"%(k,v))

# # 增加 修改 (有就修改,没就添加)
# # 添加
# infos_dict["wechat"]="lll"
# print(infos_dict)

# # 修改
# infos_dict["wechat"]="dotnetcrazy"
# print(infos_dict)

# # 删除
# del infos_dict["name"]
# del infos_dict["dog"] #不存在就报错
# print(infos_dict)

# #清空字典内容
# infos_dict.clear()
# print(infos_dict)

# # 删除字典
# del infos_dict

# 查询
infos_dict["name"]
# infos_dict["mmd"] #查不到就异常

infos_dict.get(“name”)
infos_dict.get(“mmd”)#查不到不会那些

# 查看帮助
# help(infos_dict)
len(infos_dict) #有几对key,value 
# infos_dict.has_key("name") #这个是python2里面的

View Code


NetCore:

NetCore List:

4858.com 624858.com 63

// using System;
// using System.Collections.Generic;
// using System.Linq;

// namespace aibaseConsole
// {
// public static class Program
// {
// private static void Main()
// {
// #region List
// //# 定义一个列表
// // # infos_list=[“C#”,”JavaScript”]#[]
// var infos_list = new List() { “C#”, “JavaScript” };
// // var infos_list2 = new List() { “张三”, 21 };
// // // # ###########################################################
// // // # # 遍历 for while
// // // # for item in infos_list:
// // // # print(item)
// // foreach (var item in infos_list)
// // {
// // System.Console.WriteLine(item);
// // }
// // for (int i = 0; i < infos_list.Count; i++) // // { // // System.Console.WriteLine(infos_list[i]); // // } // // // # i=0 // // // # while i // // infos_list.Add(“Java”);
// // DivPrintList(infos_list);
// // // # # 钦赐地方插入
// // // # infos_list.insert(0,”Python”)
// // // # print(infos_list)
// // infos_list.Insert(0,”Python”);
// // DivPrintList(infos_list);
// // // # # 添加2个列表
// // // # infos_list2=[“张三”,21]#python里面的列表类似于List
// // // # infos_list.extend(infos_list2)
// // // # print(infos_list)
// // infos_list.AddRange(infos_list2);
// // DivPrintList(infos_list);
// // /C#有insertRange方法 /
// // DivPrintList(infos_list2,”List2原来的列表:”);
// // infos_list2.InsertRange(0,infos_list);
// // DivPrintList(infos_list2,”List2变化后列表:”);
// // // # # help(infos_list.extend)#能够查阅etend方法描述
// // // # ###########################################################
// // // # # 删除
// // // # # pop()删除最后二个成分,重回删掉的因素
// // // # # pop(index) 删除钦点下标元素 // // // # print(infos_list.pop())
// // // # print(infos_list)
// // // # print(infos_list.pop(1))
// // // # # print(infos_list.pop(10)) #不设有就报错
// // // # print(infos_list)

// // // # # remove(“”)删除内定成分 // // // # infos_list.remove(“张三”)
// // // # # infos_list.remove(“dnt”) #不设有就报错
// // // # print(infos_list)

// // // # # del xxx[index] 删除内定下标元素 // // // # del infos_list[1]
// // // # print(infos_list)
// // // # # del infos_list[10] #不设有就报错

// // // # del infos_list #删除集合(集合再拜访就不存在了)

// // DivPrintList(infos_list);
// // infos_list.RemoveAt(1);
// // // infos_list.RemoveAt(10);//不存在则报错
// // // infos_list.RemoveRange(0,1); //可以移除多个 // // DivPrintList(infos_list);
// // infos_list.Remove(“作者家在东南吗?”); //移除钦命item,不设有不会报错
// // DivPrintList(infos_list,”清空前:”);
// // infos_list.Clear();//清空列表
// // DivPrintList(infos_list,”清空后:”);

// // // # ###########################################################
// // // # # 修改 xxx[index]=xx
// // // # # 注意:一般不引进在for循环里面修改
// // // # print(infos_list2)
// // // # infos_list2[1]=”PHP” #唯有下标修改一种方法
// // // # # infos_list2[3]=”GO” #不存在则万分 // // // # print(infos_list2)
// // DivPrintList(infos_list2);
// // infos_list2[1] = “PHP”;
// // // infos_list2[3]=”GO”; //不存在则非凡 // // DivPrintList(infos_list2);
// // // # # 想按值修改须要先查下标再修改
// // // # infos_list2.index(“张三”)
// // // # infos_list2[0]=”GO”
// // // # print(infos_list2)
// // // # # infos_list2.index(“dnt”)#不存在则不行
// // int index = infos_list2.IndexOf(“张三”);
// // infos_list2[index] = “GO”;
// // DivPrintList(infos_list2);
// // infos_list2.IndexOf(“dnt”);//不存在重临-1

// // // ###########################################################
// // // # 查询 in, not in, index, count
// // // # # for扩展:
// // // # names_list=[“张三”,”李四”,”王二麻子”]
// // var names_list=new List(){“张三”,”李四”,”王二麻子”};
// // // Console.WriteLine(names_list.Find(i=>i==”张三”));
// // // Console.WriteLine(names_list.FirstOrDefault(i=>i==”张三”));
// // Console.WriteLine(names_list.Exists(i=>i==”张三”));
// // System.Console.WriteLine(names_list.Contains(“张三”));
// // // # #张三在列表中推行操作
// // // # if “张三” in names_list:
// // // # names_list.remove(“张三”)
// // // # else:
// // // # print(names_list)

// // // # #查看”大舅子”不在列表中实践操作
// // // # if “大舅子” not in names_list:
// // // # names_list.append(“大舅子”)
// // // # else:
// // // # print(names_list)

// // // # #查询王二麻子的索引
// // // # print(names_list.index(“王二麻子”))
// // // names_list.IndexOf(“王二麻子”);

// // // # print(names_list.count(“大舅子”))
// // // # print(names_list.count(“逆天”))
// // // Console.WriteLine(names_list.Count);

// // // ###########################################################
// // // # # 排序(sort, reverse 逆置)
// // // # num_list=[1,3,5,88,7]
// // var num_list = new List() { 1, 3, 5, 88, 7 };

// // // # #倒序
// // // # num_list.reverse()
// // // # print(num_list)
// // num_list.Reverse();
// // DivPrintList(num_list);
// // // # # 从小到大排序
// // // # num_list.sort()
// // // # print(num_list)
// // num_list.Sort();
// // DivPrintList(num_list);

// // // # # 从大到小
// // // # num_list.sort(reverse=True)
// // // # print(num_list)
// // num_list.Sort();
// // num_list.Reverse();
// // DivPrintList(num_list);

// // // # ###########################################################

// // // # #列表嵌套(列表也是足以嵌套的)
// // // # num_list2=[33,44,22]
// // // # num_list.append(num_list2)
// // // # print(num_list)
// // var num_list2 = new List() { 33, 44, 22,new List(){11,55,77} };
// // DivPrintList(num_list2);//可以定义多维数组来扶助 num_list2[i][j]
// // // # for item in num_list:
// // // # print(item)
// // // # ###########################################################

// // // # # 引入Null==>None
// // // # a=[1,2,3,4]
// // // # b=[5,6]
// // // # a=a.append(b)#a.append(b)没有回来值
// // // # print(a)#None
// #endregion

// // Console.Read();
// }

// private static void DivPrintList(List list, string say = “”)
// {
// Console.WriteLine($”\n{say}”);
// foreach (var item in list)
// {
// System.Console.Write($”{item} “);
// }
// }
// }
// }

View Code

NetCore Tuple:

4858.com 644858.com 65

// using System;

// namespace aibaseConsole
// {
// public static class Program
// {
// private static void Main()
// {
// #region Tuple
// // C#中元组主若是有益程序员,不用自然可以.
// // 元祖系:
// // 值元组:
// // 比如:当您回来七个值是还是不是还用ref out 或许再次回到三个list之类的?
// // 那一个都亟待先定义,相比较麻烦.元祖在部分景况用的相比较多 eg:

// // 初始化
// // var test_tuple = (“萌萌哒”, 1, 3, 5, “加息”, “加息”); //那种方法就是valueTuple了

// // test_tuple.Item1 = “ddd”;//可以修改值

// // test_tuple.GetType();
// // test_tuple.itemxxx //获取值只好通过itemxxx

// var result = GetCityAndTel(); //扶助async/await方式 // var city = result.city;
// var tel = result.tel;
// // 拆包方式:
// var (city1, tel1) = GetCityAndTel();

// #endregion
// // Console.Read();
// }
// // public static (string city, string tel) GetCityAndTel()
// // {
// // return (“新加坡”, “110”);
// // }
// // 简化写法
// public static (string city, string tel) GetCityAndTel() => (“巴黎”, “110”);
// }
// }

View Code

NetCore Dict:

4858.com 664858.com 67

using System;
using System.Collections.Generic;

namespace aibaseConsole
{
public static class Program
{
private static void Main()
{

            #region Dict
            // infos_dict={"name":"dnt","web":"dkill.net"}
            // # # 遍历
            // # for item in infos_dict.keys():
            // #     print(item)
            // # for item in infos_dict.values():
            // #     print(item)
            // # for item in infos_dict.items():
            // #     print("Key:%s,Value:%s"%(item[0],item[1]))
            // # #每一次相当于取一个元组,那可以用之前讲的例子来简化了:c,d=a #等价于:c=a[0] d=a[1]
            // # for k,v in infos_dict.items():
            // #     print("Key:%s,Value:%s"%(k,v))
            var infos_dict = new Dictionary<string, object>{
                {"name","dnt"},
                {"web","dkill.net"}
            };
            // foreach (var item in infos_dict.Keys)
            // {
            //     System.Console.WriteLine(item);
            // }
            // foreach (var item in infos_dict.Values)
            // {
            //     System.Console.WriteLine(item);
            // }
            // foreach (KeyValuePair<string, object> kv in infos_dict)
            // {
            //     //    System.Console.WriteLine("Key:%s,Value:%s",(kv.Key,kv.Value));
            //     System.Console.WriteLine($"Key:{kv.Key},Value:{kv.Value}");
            // }

// // # # 增加 修改 (有就修改,没就拉长)
// // # # 添加
// // # infos_dict[“wechat”]=”lll”
// // # print(infos_dict)
// infos_dict.Add(“wechat”, “lll”);
// infos_dict[“wechat1”] = “lll”;
// // # # 修改
// // # infos_dict[“wechat”]=”dotnetcrazy”
// // # print(infos_dict)
// infos_dict[“wechat”] = “dotnetcrazy”;

// // # # 删除
// // # del infos_dict[“name”]
// // # del infos_dict[“dog”] #不存在就报错
// // # print(infos_dict)
// infos_dict.Remove(“name”);
// infos_dict.Remove(“dog”);
// // # #清空列表内容
// // # infos_dict.clear()
// // # print(infos_dict)
// infos_dict.Clear();
// // # # 删除列表
// // # del infos_dict

// # 查询
// infos_dict[“name”]
// infos_dict[“mmd”] #查不到就分外

// infos_dict.get(“name”)
// infos_dict.get(“mmd”)#查不到不会要命
Console.WriteLine(infos_dict[“name”]);
// Console.WriteLine(infos_dict[“mmd”]); //#查不到就这多少个 // 先看看有没有 ContainsKey(key),看值就 ContainsValue(value)
if (infos_dict.ContainsKey(“mmd”)) Console.WriteLine(infos_dict[“mmd”]);

// # 查看辅助 // help(infos_dict)
// len(infos_dict) #有几对key,value
Console.WriteLine(infos_dict.Count);

            #endregion

// Console.Read();
}
}
}

View Code

列表删除成分的不二法门,del list[index],list.pop(index),list.remove(s)

多个等号是赋值,五个等号是相比较。

字典的删减格局,del dict[key], dict.pop(key)

 

set的去除方式,set.pop(),set.remove(s)

2.字符串

4858.com 684858.com 69

a1=’abs’

1 set1.pop()  # 删除最后一个,但最后一个是随机的,所以可认为随机删除
2 print(set1)
3 
4 set1.remove("15")
5 print(set1)

a2=”sdf”

View Code

a3=”””nsdfis”””

 

 

用户注册登录序列

 字符串方法:

4858.com 704858.com 71

S = “guifeng”

 1 user_dict = {}
 2 user_list = []
 3 log = True
 4 
 5 def prelog():
 6     active = True
 7     while active:
 8         user_name = input("请输入你的昵称")
 9         len_username = len(user_name)
10         if len_username > 6 and len_username < 20:
11             while active:
12                 user_pass = input("请输入你的密码")
13                 len_userpass = len(user_pass)
14                 if len_userpass > 8 and len_userpass < 20:
15                     while active:
16                         user_age = input("请输入你的年龄")
17                         if  user_age.isdigit():
18                             user_dict['昵称'] = user_name
19                             user_dict['密码'] = user_pass
20                             user_dict['年龄'] = user_age
21                             user_list.append(user_dict)
22                             active = False
23                         else:
24                             print("请输入纯数字")
25                             continue
26                 else:
27                     print("密码长度不合法")
28                     continue
29         else:
30             print("昵称长度不合法")
31             continue
32 
33 def login():
34     signal2 = True
35     while True:
36         if signal2:
37             global log
38             log = False
39             signal = False
40             user_name = input("请输入你的用户名")
41             user_pass = input("请输入你的密码")
42             for e in user_list:
43                 if e.get("昵称") == user_name:
44                     real_pass = e["密码"]
45                     if real_pass == user_pass:
46                         signal = True
47                         print("登录成功")
48                         print("运行成功")
49                         ask = input("是否退出?y/n")
50                         if ask == 'y':
51                             signal2 = False
52                             log = True
53                             break  # 直接退出for循环
54                         else:
55                             signal2 = False
56                             break  #直接退出for循环
57             if not signal:
58                 print("用户名或者密码错误")
59                 continue
60         else:
61             break  # 直接退出while循环
62 
63 while True:
64     choice = input("""1.注册
65 2.登录
66 3.注销
67 4.退出
68     """)
69     if choice == '1':
70         prelog()
71     elif choice == '2':
72         if log == True:
73             login()
74             # continue
75         else:
76             print("用户接口被占用")
77     elif choice == '3':
78         if log == True:
79             print("无用户登录")
80         else:
81             log = True
82     elif choice == '4':
83         if log == True:
84             break
85         else:
86             print("请先注销")
87     else:
88         print("请输入1-4")
capitalize()  #  首字母变大写
S.capitalize()

def center(self, width, fillchar=None):  
        """ 内容居中,width:总长度;fillchar:空白处填充内容,默认无 """

 def count(self, sub, start=None, end=None):  
        """ 子序列个数 """
        """
        S.count(sub[, start[, end]]) -> int

def decode(self, encoding=None, errors=None):  
        """ 解码 """

def encode(self, encoding=None, errors=None):  
        """ 编码,针对unicode """

def endswith(self, suffix, start=None, end=None):  
        """ 是否以 xxx 结束 """

def expandtabs(self, tabsize=None):  
        """ 将tab转换成空格,默认一个tab转换成8个空格 """

def find(self, sub, start=None, end=None):  
        """ 寻找子序列位置,如果没找到,返回 -1 """

 def isalnum(self):  
        """ 是否是字母和数字 """

 def isalpha(self):  
        """ 是否是字母 """

 def isdigit(self):  
        """ 是否是数字 """

 def islower(self):  
        """ 是否小写 """

def join(self, iterable):  
        """ 连接 """

 def ljust(self, width, fillchar=None):  

        """ 内容左对齐,右侧填充 """

  def lower(self):  
        """ 变小写 """

 def lstrip(self, chars=None):  
        """ 移除左侧空白 """

    def partition(self, sep):  
        """ 分割,前,中,后三部分 """
        """
        S.partition(sep) -> (head, sep, tail)

  def replace(self, old, new, count=None):  
        """ 替换 """

   def startswith(self, prefix, start=None, end=None):  
        """ 是否起始 """

  def strip(self, chars=None):  
        """ 移除两段空白 """

    def swapcase(self):  
        """ 大写变小写,小写变大写 """

View Code

4858.com 724858.com 73

 

class str(basestring):
    """
    str(object='') -> string

    Return a nice string representation of the object.
    If the argument is a string, the return value is the same object.
    """
    def capitalize(self):  
        """ 首字母变大写 """
        """
        S.capitalize() -> string

        Return a copy of the string S with only its first character
        capitalized.
        """
        return ""

    def center(self, width, fillchar=None):  
        """ 内容居中,width:总长度;fillchar:空白处填充内容,默认无 """
        """
        S.center(width[, fillchar]) -> string

        Return S centered in a string of length width. Padding is
        done using the specified fill character (default is a space)
        """
        return ""

    def count(self, sub, start=None, end=None):  
        """ 子序列个数 """
        """
        S.count(sub[, start[, end]]) -> int

        Return the number of non-overlapping occurrences of substring sub in
        string S[start:end].  Optional arguments start and end are interpreted
        as in slice notation.
        """
        return 0

    def decode(self, encoding=None, errors=None):  
        """ 解码 """
        """
        S.decode([encoding[,errors]]) -> object

        Decodes S using the codec registered for encoding. encoding defaults
        to the default encoding. errors may be given to set a different error
        handling scheme. Default is 'strict' meaning that encoding errors raise
        a UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
        as well as any other name registered with codecs.register_error that is
        able to handle UnicodeDecodeErrors.
        """
        return object()

    def encode(self, encoding=None, errors=None):  
        """ 编码,针对unicode """
        """
        S.encode([encoding[,errors]]) -> object

        Encodes S using the codec registered for encoding. encoding defaults
        to the default encoding. errors may be given to set a different error
        handling scheme. Default is 'strict' meaning that encoding errors raise
        a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
        'xmlcharrefreplace' as well as any other name registered with
        codecs.register_error that is able to handle UnicodeEncodeErrors.
        """
        return object()

    def endswith(self, suffix, start=None, end=None):  
        """ 是否以 xxx 结束 """
        """
        S.endswith(suffix[, start[, end]]) -> bool

        Return True if S ends with the specified suffix, False otherwise.
        With optional start, test S beginning at that position.
        With optional end, stop comparing S at that position.
        suffix can also be a tuple of strings to try.
        """
        return False

    def expandtabs(self, tabsize=None):  
        """ 将tab转换成空格,默认一个tab转换成8个空格 """
        """
        S.expandtabs([tabsize]) -> string

        Return a copy of S where all tab characters are expanded using spaces.
        If tabsize is not given, a tab size of 8 characters is assumed.
        """
        return ""

    def find(self, sub, start=None, end=None):  
        """ 寻找子序列位置,如果没找到,返回 -1 """
        """
        S.find(sub [,start [,end]]) -> int

        Return the lowest index in S where substring sub is found,
        such that sub is contained within S[start:end].  Optional
        arguments start and end are interpreted as in slice notation.

        Return -1 on failure.
        """
        return 0

    def format(*args, **kwargs): # known special case of str.format
        """ 字符串格式化,动态参数,将函数式编程时细说 """
        """
        S.format(*args, **kwargs) -> string

        Return a formatted version of S, using substitutions from args and kwargs.
        The substitutions are identified by braces ('{' and '}').
        """
        pass

    def index(self, sub, start=None, end=None):  
        """ 子序列位置,如果没找到,报错 """
        S.index(sub [,start [,end]]) -> int

        Like S.find() but raise ValueError when the substring is not found.
        """
        return 0

    def isalnum(self):  
        """ 是否是字母和数字 """
        """
        S.isalnum() -> bool

        Return True if all characters in S are alphanumeric
        and there is at least one character in S, False otherwise.
        """
        return False

    def isalpha(self):  
        """ 是否是字母 """
        """
        S.isalpha() -> bool

        Return True if all characters in S are alphabetic
        and there is at least one character in S, False otherwise.
        """
        return False

    def isdigit(self):  
        """ 是否是数字 """
        """
        S.isdigit() -> bool

        Return True if all characters in S are digits
        and there is at least one character in S, False otherwise.
        """
        return False

    def islower(self):  
        """ 是否小写 """
        """
        S.islower() -> bool

        Return True if all cased characters in S are lowercase and there is
        at least one cased character in S, False otherwise.
        """
        return False

    def isspace(self):  
        """
        S.isspace() -> bool

        Return True if all characters in S are whitespace
        and there is at least one character in S, False otherwise.
        """
        return False

    def istitle(self):  
        """
        S.istitle() -> bool

        Return True if S is a titlecased string and there is at least one
        character in S, i.e. uppercase characters may only follow uncased
        characters and lowercase characters only cased ones. Return False
        otherwise.
        """
        return False

    def isupper(self):  
        """
        S.isupper() -> bool

        Return True if all cased characters in S are uppercase and there is
        at least one cased character in S, False otherwise.
        """
        return False

    def join(self, iterable):  
        """ 连接 """
        """
        S.join(iterable) -> string

        Return a string which is the concatenation of the strings in the
        iterable.  The separator between elements is S.
        """
        return ""

    def ljust(self, width, fillchar=None):  
        """ 内容左对齐,右侧填充 """
        """
        S.ljust(width[, fillchar]) -> string

        Return S left-justified in a string of length width. Padding is
        done using the specified fill character (default is a space).
        """
        return ""

    def lower(self):  
        """ 变小写 """
        """
        S.lower() -> string

        Return a copy of the string S converted to lowercase.
        """
        return ""

    def lstrip(self, chars=None):  
        """ 移除左侧空白 """
        """
        S.lstrip([chars]) -> string or unicode

        Return a copy of the string S with leading whitespace removed.
        If chars is given and not None, remove characters in chars instead.
        If chars is unicode, S will be converted to unicode before stripping
        """
        return ""

    def partition(self, sep):  
        """ 分割,前,中,后三部分 """
        """
        S.partition(sep) -> (head, sep, tail)

        Search for the separator sep in S, and return the part before it,
        the separator itself, and the part after it.  If the separator is not
        found, return S and two empty strings.
        """
        pass

    def replace(self, old, new, count=None):  
        """ 替换 """
        """
        S.replace(old, new[, count]) -> string

        Return a copy of string S with all occurrences of substring
        old replaced by new.  If the optional argument count is
        given, only the first count occurrences are replaced.
        """
        return ""

    def rfind(self, sub, start=None, end=None):  
        """
        S.rfind(sub [,start [,end]]) -> int

        Return the highest index in S where substring sub is found,
        such that sub is contained within S[start:end].  Optional
        arguments start and end are interpreted as in slice notation.

        Return -1 on failure.
        """
        return 0

    def rindex(self, sub, start=None, end=None):  
        """
        S.rindex(sub [,start [,end]]) -> int

        Like S.rfind() but raise ValueError when the substring is not found.
        """
        return 0

    def rjust(self, width, fillchar=None):  
        """
        S.rjust(width[, fillchar]) -> string

        Return S right-justified in a string of length width. Padding is
        done using the specified fill character (default is a space)
        """
        return ""

    def rpartition(self, sep):  
        """
        S.rpartition(sep) -> (head, sep, tail)

        Search for the separator sep in S, starting at the end of S, and return
        the part before it, the separator itself, and the part after it.  If the
        separator is not found, return two empty strings and S.
        """
        pass

    def rsplit(self, sep=None, maxsplit=None):  
        """
        S.rsplit([sep [,maxsplit]]) -> list of strings

        Return a list of the words in the string S, using sep as the
        delimiter string, starting at the end of the string and working
        to the front.  If maxsplit is given, at most maxsplit splits are
        done. If sep is not specified or is None, any whitespace string
        is a separator.
        """
        return []

    def rstrip(self, chars=None):  
        """
        S.rstrip([chars]) -> string or unicode

        Return a copy of the string S with trailing whitespace removed.
        If chars is given and not None, remove characters in chars instead.
        If chars is unicode, S will be converted to unicode before stripping
        """
        return ""

    def split(self, sep=None, maxsplit=None):  
        """ 分割, maxsplit最多分割几次 """
        """
        S.split([sep [,maxsplit]]) -> list of strings

        Return a list of the words in the string S, using sep as the
        delimiter string.  If maxsplit is given, at most maxsplit
        splits are done. If sep is not specified or is None, any
        whitespace string is a separator and empty strings are removed
        from the result.
        """
        return []

    def splitlines(self, keepends=False):  
        """ 根据换行分割 """
        """
        S.splitlines(keepends=False) -> list of strings

        Return a list of the lines in S, breaking at line boundaries.
        Line breaks are not included in the resulting list unless keepends
        is given and true.
        """
        return []

    def startswith(self, prefix, start=None, end=None):  
        """ 是否起始 """
        """
        S.startswith(prefix[, start[, end]]) -> bool

        Return True if S starts with the specified prefix, False otherwise.
        With optional start, test S beginning at that position.
        With optional end, stop comparing S at that position.
        prefix can also be a tuple of strings to try.
        """
        return False

    def strip(self, chars=None):  
        """ 移除两段空白 """
        """
        S.strip([chars]) -> string or unicode

        Return a copy of the string S with leading and trailing
        whitespace removed.
        If chars is given and not None, remove characters in chars instead.
        If chars is unicode, S will be converted to unicode before stripping
        """
        return ""

    def swapcase(self):  
        """ 大写变小写,小写变大写 """
        """
        S.swapcase() -> string

        Return a copy of the string S with uppercase characters
        converted to lowercase and vice versa.
        """
        return ""

    def title(self):  
        """
        S.title() -> string

        Return a titlecased version of S, i.e. words start with uppercase
        characters, all remaining cased characters have lowercase.
        """
        return ""

    def translate(self, table, deletechars=None):  
        """
        转换,需要先做一个对应表,最后一个表示删除字符集合
        intab = "aeiou"
        outtab = "12345"
        trantab = maketrans(intab, outtab)
        str = "this is string example....wow!!!"
        print str.translate(trantab, 'xm')
        """

        """
        S.translate(table [,deletechars]) -> string

        Return a copy of the string S, where all characters occurring
        in the optional argument deletechars are removed, and the
        remaining characters have been mapped through the given
        translation table, which must be a string of length 256 or None.
        If the table argument is None, no translation is applied and
        the operation simply removes the characters in deletechars.
        """
        return ""

    def upper(self):  
        """
        S.upper() -> string

        Return a copy of the string S converted to uppercase.
        """
        return ""

    def zfill(self, width):  
        """方法返回指定长度的字符串,原字符串右对齐,前面填充0。"""
        """
        S.zfill(width) -> string

        Pad a numeric string S with zeros on the left, to fill a field
        of the specified width.  The string S is never truncated.
        """
        return ""

    def _formatter_field_name_split(self, *args, **kwargs): # real signature unknown
        pass

    def _formatter_parser(self, *args, **kwargs): # real signature unknown
        pass

    def __add__(self, y):  
        """ x.__add__(y) <==> x+y """
        pass

    def __contains__(self, y):  
        """ x.__contains__(y) <==> y in x """
        pass

    def __eq__(self, y):  
        """ x.__eq__(y) <==> x==y """
        pass

    def __format__(self, format_spec):  
        """
        S.__format__(format_spec) -> string

        Return a formatted version of S as described by format_spec.
        """
        return ""

    def __getattribute__(self, name):  
        """ x.__getattribute__('name') <==> x.name """
        pass

    def __getitem__(self, y):  
        """ x.__getitem__(y) <==> x[y] """
        pass

    def __getnewargs__(self, *args, **kwargs): # real signature unknown
        pass

    def __getslice__(self, i, j):  
        """
        x.__getslice__(i, j) <==> x[i:j]

                   Use of negative indices is not supported.
        """
        pass

    def __ge__(self, y):  
        """ x.__ge__(y) <==> x>=y """
        pass

    def __gt__(self, y):  
        """ x.__gt__(y) <==> x>y """
        pass

    def __hash__(self):  
        """ x.__hash__() <==> hash(x) """
        pass

    def __init__(self, string=''): # known special case of str.__init__
        """
        str(object='') -> string

        Return a nice string representation of the object.
        If the argument is a string, the return value is the same object.
        # (copied from class doc)
        """
        pass

    def __len__(self):  
        """ x.__len__() <==> len(x) """
        pass

    def __le__(self, y):  
        """ x.__le__(y) <==> x<=y """
        pass

    def __lt__(self, y):  
        """ x.__lt__(y) <==> x<y """
        pass

    def __mod__(self, y):  
        """ x.__mod__(y) <==> x%y """
        pass

    def __mul__(self, n):  
        """ x.__mul__(n) <==> x*n """
        pass

    @staticmethod # known case of __new__
    def __new__(S, *more):  
        """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
        pass

    def __ne__(self, y):  
        """ x.__ne__(y) <==> x!=y """
        pass

    def __repr__(self):  
        """ x.__repr__() <==> repr(x) """
        pass

    def __rmod__(self, y):  
        """ x.__rmod__(y) <==> y%x """
        pass

    def __rmul__(self, n):  
        """ x.__rmul__(n) <==> n*x """
        pass

    def __sizeof__(self):  
        """ S.__sizeof__() -> size of S in memory, in bytes """
        pass

    def __str__(self):  
        """ x.__str__() <==> str(x) """
        pass

str

字符串

 

 

3.布尔值
True/False

 

4.列表:

 

name_list = [“a”,”b”,”s”]

索引
print name-list[0]

切片

name_list[0,2]

len
print name-list[2,name_lixnt.len()]

向后面扩张:
append

name_list.append(“d”)

统计成分出现次数
count
name_list.count(“d”)

#iterable 可迭代的

伸张,相当于批量日增
extend
l = [“1″,”2”]
name_list.extend(l)

取得内定索引
index
name_list.index(“a”)

插入,钦命索引位置插入
insert
name_list.insert(1,”sb”)

去掉列表的结尾三个。
pop
name_list.pop()

移除左边找到的首先个有些成分,
remove
name_list.remove(“s”)

反转列表
reverse
name_list.reverse()

除去钦定索引号成分

del name_list[1]
del name_list[1:3]

列表排序
sort
name_list.sort()

4858.com 744858.com 75

class list(object):
    """
    list() -> new empty list
    list(iterable) -> new list initialized from iterable's items
    """
    def append(self, p_object): # real signature unknown; restored from __doc__
        """ L.append(object) -- append object to end """
        pass

    def count(self, value): # real signature unknown; restored from __doc__
        """ L.count(value) -> integer -- return number of occurrences of value """
        return 0

    def extend(self, iterable): # real signature unknown; restored from __doc__
        """ L.extend(iterable) -- extend list by appending elements from the iterable """
        pass

    def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
        """
        L.index(value, [start, [stop]]) -> integer -- return first index of value.
        Raises ValueError if the value is not present.
        """
        return 0

    def insert(self, index, p_object): # real signature unknown; restored from __doc__
        """ L.insert(index, object) -- insert object before index """
        pass

    def pop(self, index=None): # real signature unknown; restored from __doc__
        """
        L.pop([index]) -> item -- remove and return item at index (default last).
        Raises IndexError if list is empty or index is out of range.
        """
        pass

    def remove(self, value): # real signature unknown; restored from __doc__
        """
        L.remove(value) -- remove first occurrence of value.
        Raises ValueError if the value is not present.
        """
        pass

    def reverse(self): # real signature unknown; restored from __doc__
        """ L.reverse() -- reverse *IN PLACE* """
        pass

    def sort(self, cmp=None, key=None, reverse=False): # real signature unknown; restored from __doc__
        """
        L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
        cmp(x, y) -> -1, 0, 1
        """
        pass

    def __add__(self, y): # real signature unknown; restored from __doc__
        """ x.__add__(y) <==> x+y """
        pass

    def __contains__(self, y): # real signature unknown; restored from __doc__
        """ x.__contains__(y) <==> y in x """
        pass

    def __delitem__(self, y): # real signature unknown; restored from __doc__
        """ x.__delitem__(y) <==> del x[y] """
        pass

    def __delslice__(self, i, j): # real signature unknown; restored from __doc__
        """
        x.__delslice__(i, j) <==> del x[i:j]

                   Use of negative indices is not supported.
        """
        pass

    def __eq__(self, y): # real signature unknown; restored from __doc__
        """ x.__eq__(y) <==> x==y """
        pass

    def __getattribute__(self, name): # real signature unknown; restored from __doc__
        """ x.__getattribute__('name') <==> x.name """
        pass

    def __getitem__(self, y): # real signature unknown; restored from __doc__
        """ x.__getitem__(y) <==> x[y] """
        pass

    def __getslice__(self, i, j): # real signature unknown; restored from __doc__
        """
        x.__getslice__(i, j) <==> x[i:j]

                   Use of negative indices is not supported.
        """
        pass

    def __ge__(self, y): # real signature unknown; restored from __doc__
        """ x.__ge__(y) <==> x>=y """
        pass

    def __gt__(self, y): # real signature unknown; restored from __doc__
        """ x.__gt__(y) <==> x>y """
        pass

    def __iadd__(self, y): # real signature unknown; restored from __doc__
        """ x.__iadd__(y) <==> x+=y """
        pass

    def __imul__(self, y): # real signature unknown; restored from __doc__
        """ x.__imul__(y) <==> x*=y """
        pass

    def __init__(self, seq=()): # known special case of list.__init__
        """
        list() -> new empty list
        list(iterable) -> new list initialized from iterable's items
        # (copied from class doc)
        """
        pass

    def __iter__(self): # real signature unknown; restored from __doc__
        """ x.__iter__() <==> iter(x) """
        pass

    def __len__(self): # real signature unknown; restored from __doc__
        """ x.__len__() <==> len(x) """
        pass

    def __le__(self, y): # real signature unknown; restored from __doc__
        """ x.__le__(y) <==> x<=y """
        pass

    def __lt__(self, y): # real signature unknown; restored from __doc__
        """ x.__lt__(y) <==> x<y """
        pass

    def __mul__(self, n): # real signature unknown; restored from __doc__
        """ x.__mul__(n) <==> x*n """
        pass

    @staticmethod # known case of __new__
    def __new__(S, *more): # real signature unknown; restored from __doc__
        """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
        pass

    def __ne__(self, y): # real signature unknown; restored from __doc__
        """ x.__ne__(y) <==> x!=y """
        pass

    def __repr__(self): # real signature unknown; restored from __doc__
        """ x.__repr__() <==> repr(x) """
        pass

    def __reversed__(self): # real signature unknown; restored from __doc__
        """ L.__reversed__() -- return a reverse iterator over the list """
        pass

    def __rmul__(self, n): # real signature unknown; restored from __doc__
        """ x.__rmul__(n) <==> n*x """
        pass

    def __setitem__(self, i, y): # real signature unknown; restored from __doc__
        """ x.__setitem__(i, y) <==> x[i]=y """
        pass

    def __setslice__(self, i, j, y): # real signature unknown; restored from __doc__
        """
        x.__setslice__(i, j, y) <==> x[i:j]=y

                   Use  of negative indices is not supported.
        """
        pass

    def __sizeof__(self): # real signature unknown; restored from __doc__
        """ L.__sizeof__() -- size of L in memory, in bytes """
        pass

    __hash__ = None

list

列表

 

5.元组 tuple

元组很列表差不离千篇一律,不过列表是可以修改的,元组是不可以改改的。

name_tuple=(“a”,”b”)

索引

name_tuple[0]

len
print name_tuple(len(name_tuple)-1)

切片
print name_tuple[0:1]

for

for i in name_tuple:

收获成分的目录地点

name_tuple(“a”)

总结成分出现的个数
def count(self, value):

得到钦定成分索引地点
def index(self, value, start=None, stop=None)

 

6.字典 dict

#字典的各样成分,键值对

 

user_info={

“name”:”sb”,
“age”:42,
“gender”:”man”

}
#索引
print user_info[“name”]

循环

for i in user_info: #默许只输出key
print i

print user_info.key() #拿到具有的key
print user_info.values() # 获取具有values
print user_info.items() #收获具有键值对

for k,v user_info.items():
print k,v

免除全部内容
clear
user_info.clear()

get 按照key获取值,如果key不设有,可以钦赐暗许值

user_info.get(“a”,123)

def pop(self, k, d=None) 可以内定key
“”” 获取并在字典中移除

user_info.pop(“age”)

def popitem(self): 由后往前
user_info.popitem()
print user_info
“”” 获取并在字典中移除 “””

履新字典:
update
test= {
“a”=1
“s”=2
}
user_info.update(test)

删除

del user_info(“value”)

 

 7.enumrate

自动生成一列,默许0自增
enumrate
li = [“电脑”,”别墅”,”美女”]
for k,v in enumerate(li, 1):
print(k,v)

 

 

8.range和xrange  

点名范围,生成钦命的数字

print range(1, 10)
# 结果:[1, 2, 3, 4, 5, 6, 7, 8, 9]

print range(1, 10, 2)
# 结果:[1, 3, 5, 7, 9]

print range(30, 0, -2)
# 结果:[30, 28, 26, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2]  

 

 

# 三元运算
# name = 值1  if 条件 esle 值2
if 1==1:
    name="alxe"
else:
    name="eric"
#三元运算

name = "alxe" if 1==1 else "eric"
print(name)

# 如果条件成立,那么将 “值1” 赋值给result变量,否则,将“值2”赋值给result变量

#深浅拷贝
# 1.对于 数字 和 字符串 而言,赋值、浅拷贝和深拷贝无意义,因为其永远指向同一个内存地址。
import copy

n1 = 123
# ## 浅拷贝 ##
n2 = copy.copy(n1)
print(id(n2))

# ## 深拷贝 ##
n3 = copy.deepcopy(n1)
print(id(n3))

# # 对于字典、元祖、列表 而言,进行赋值、浅拷贝和深拷贝时,其内存地址的变化是不同的。
#
# 1、赋值
#
# 赋值,只是创建一个变量,该变量指向原来内存地址

# 2、浅拷贝

# 浅拷贝,在内存中只额外创建第一层数据

# 3、深拷贝
#
# 深拷贝,在内存中将所有的数据重新创建一份(排除最后一层,即:python内部对字符串和数字的优化)

 

发表评论

电子邮件地址不会被公开。 必填项已用*标注

Copyright @ 2010-2019 美高梅手机版4858 版权所有