python 基本数据类型

一、运算符

1.算数运算:

+  加  两个对象相加

-  减   两个对象相减 或是得到负数

*  乘  两个对象相乘  或是返回一个被重复若干次的字符串

/   除  两个对象相除  

** 幂  一个数的指数 

% 取模 返回除法的余数

// 返回商的整数部分 地板除 

 

2.赋值运算 

=  等于赋值运算符   start = start

+=  加法赋值运算符  start = start+1

-= 减法赋值运算符   start = start- 1

*=  乘法赋值运算符  start = start* 1 

/= 除法赋值运算符  start= start/1

%=  取余数赋值运算符  start = start%1

//  取整数赋值运算符   start = start//1

 

3.比较运算  比较运算符 都是返回一个布尔值

==  比较等式两边是否相等  如果相等则返回false

>=  比较是否大于等于   如果是返回false

> 比较是否大于    如果是返回false

!=  比较是否不等于  如果不等于返回true

<>比较是否不等于  如果不等于返回true

< 比较是否小于  如果是返回true

<= 比较是否小于等于  如果是返回true

 

4.逻辑运算符

and   布尔值’与‘

or    布尔值”或“

not   布尔值”非“

 

5.成员运算符

in  如果在指定的序列中找到成员 则返回true,否则返回false

not in  如果在指定成员序列中找不到成员 返回true,否则false

 

二、基本的数据类型

1.int 整数型

在32位的计算机上,整数的位数位32位,它的取值范围是—2**31——   2**32 -1 

在64位的计算机上,整数的位数为64位,它的取值范围是-2**63——  2**63 -1

int:

(1)bit_length 返回表示该数字用的最少位数

(2)__add__()  相加  等于 x+y

(3)__div__()除以   等于 x/y

2.布尔值 

真或假 

0或1 

 

 

3.str 字符串

”hello world“

字符串的常用功能:

切片  

索引  find  index  find只有字符串里有 

x = (”123456789“)
if x.find("12"):
    print('yes')
else:
    print('no')
#输出结果应为 no  

x = (’123456789‘)
if x.find("2121"):
    print('yes')
else:
    print("no")

#输出结果应为no

#结论  在if 语句下 如果str包含要查找的对象 则会返回no  不包含会返回yes 

 

移除空白  strip  如果要移除左边的空白即为lstrip 右侧即为rstrip

分割    partation  以某字符或字符串为分割符

长度   len

首字母变大写 capitalize    字母小写变大写大写变小写 swapcase  

居中 center  

title  标题 

decode  解码

encode 编码

将tab转换成空格 默认一个tab为8个空格  expendtabs 

寻找子序列位置,如果没找到返回 -1(1)  find 

子序列位置,如果没找到报错   index

替换 replace   句型   x.replace(old,new)

translate 翻译  需要先做一个对应表,最后表示删除字符集和

 

4.list 列表 大括号 

列表是逐级嵌套的 想打开只需要在列表主体的后面依次的写入表达位置的索引即可

索引:

 (1) index 在列表中找到某个值第一个匹配的索引位置, x = [123,456] pirnt(x.index(456))  输出结果应为1

 (2) count  在列表中查看某元素在列表中有几个

x = ["123","456"]
y = x.count("123")
print(y)

#其结果为 1

切片:

x = ['123','456','789']
print(x[:1])

#此时输出的应为 [’123‘]

 

追加:  

(1)append  在列表末尾添加新的对象  写法  x = [123,456]    x.append(22)  print(x) 结果为(123,456,22)

(2)extend  在末尾批量加入新的对象  写法   x= [123,456] y = [789,iop]  x.extend(y)  print(x)   结果为(123,456,789,lop)

 (3) insert    将对象插入当前列表的某一位置   x = [123,456] y =x.insert("2,hello") print(x)  结果为 [123,456,hello]

删除

(1)remove  移除某列表中第一个匹配项

x = ["123","456"]
y = x.remove("123")
print(x)

#结果为 ["456"]

(2)pop  移除列表中最后一个匹配项,并返回其值

x = ['123','456','789']
y = x.pop()
print(x)

#其结果为 ["123","456"]

#如果print(y) 结果为["789'] 

 

长度              len

x = ["123","456","789"]
print(len(x))

#此时输出结果应为3

循环                for in

x = ["123","456"]
for y  in x:
    print(y)

#此时结果应为
#”123“
#”456“

重复        print(x*4) 重复输出4遍

反向                reverse

x = ["123","456","789"]
y = x.reverse()
print(x)

#其结果为 ["789","456","123"]

 

连接                join 方法用于将序列中的元素以指定的字符连接生成一个新的字符串。

x = ['123','456','789']
y = ("-")
print(y.join(x))


#结果为 123-456-789

排序            sort  用于对原有的列表进行重新排序,如使用参数,则按指定的函数比较函数。

x = ["ftp","abc","tkk"];
x.sort();
print(x)

#结果为 ["abc","ftp","tkk"]

 

5.元组

索引

(1)index  查找元素在元组的位置,查不到报错

(2)count 查找元素在元组中一共有几个  查不到报0 

长度  len

x = (’123‘,’423‘,’222‘)
print(len(x))
#此时结果应为3

循环

x = ('123','456','789')
for i in x:
    print(i)

#此时输出结果应为 ”123“  ”456“  ”789“

 

包含

切片

x = ('123','456','789')
print(x[2:])
#此时输出应为789

 

6.字典  Dictionary

字典是另一种可变容器模型,且可以存储任意类型对象,字典中每个键(key)与值(value)所组

成的键值对用:分割开,两组键值对用,隔开,整个字典包含在花括号中。字典的键必须是唯一的,但值则不必。

格式如下:
dictionary = {
         ”123“:”1“,
         ”456“:”2“,
          ”789“: ”3“ 
    

}
print(dictionary["123"])
#结果为 1

 

增加与修改 

dictionary = {
      ”1“:”123“,
      ”2“:”456“,
       ”3“:”789“

}


dictionary["1"] = "666"  #update existing entry 增加现有项
dictionary["4"] = "hello world"  #add new entry   增加新项


print(”1“)  #结果为666
print(”4“)  #结果为 hello world

 

删除 del删除条目或字典  clear 清除字典内的信息

 

dictionary = {
        "123":1,
        "456":2,
        "789":3


}
dictionary.clear          # 清除字典内容
del dictionary["123"] # 删除条目 
del dictionary            #  删除字典

prin(dictionary)   
                           

                                  #结果依次为 {}
                                  #{“456“:2,”789“:3}
                                  #<type'dictionary'>

字典的值可以没有限制的取任何对象,既可以是标准对象,又可以是用户定义的,但键不可以

两个重要的点需要记住:

1.如果字典中含有相同的键名,那么输出时会输出靠后的键对应的值。

dictionary = {
        ”123“:”1“,
        ”456“:”2“,
        ”123“:”3“

}
print(dictionary["123"])  #结果为3

2.键必须不可以变所以可以用数字,字符串,元祖,去充当,而列表不行:

dictionary = {
           ["123"]:"1",
           "456":"2"


}
print(dictionary)   


#此时会报错
C:\Python27\python.exe C:/Users/Administrator/PycharmProjects/yang1/c1.py
Traceback (most recent call last):
  File "C:/Users/Administrator/PycharmProjects/yang1/c1.py", line 2, in <module>
    ["1"] : "123",
TypeError: unhashable type: 'list'

字典内置函数与使用方法

函数

1.cmp 比较两个字典的大小  python3里面已经没有cmp函数  使用需要引用 import opreator

dictionary = {
        "1"= "123"  

}


dictionary2 ={
          "1" = "123"


} 

print(cmp(dictionary,dictionary2))

#此时输出结果为0 如果字典1大于字典2 则返回1  小于则返回-1

 

2.len() 计算字典的键值对个数 

dictionary = {
         ”123“= ”1“,
         ”456“= ”2“

}
print(len(dictionary))
#此时输出结果为2

 

3.type  返回输入的变量类型

dictionary = {
        ”1“= ”123“

}
print(type(dictionary))
#其结果为<type'dict'>

4.str  输出字典可以打印的字符串表示。

 

方法

1.clear 清除字典内所有的元素

2.copy

dict = {

         ”user“:”123“,
         ”password“:["456","789"]



}
dict2 = dict                         #只是dict的别名
dict3 = dict.copy()              #浅拷贝:深拷贝父对象一级目录,子对象二级目录不拷贝,还是引用

dict["user"] = "lichao"
dict["possword"].remove("456")
print(dict2)        # user:456   password:789
print(dict3)        # user:123   password:789 

实例中 dict2 其实是 dict1 的引用(别名),所以输出结果都是一致的,dict3 父对象进行了深拷贝,不会随dict1 修改而修改,子对象是浅拷贝所以随 dict1 的修改而修改。

3.fromkeys  创建新字典,以序列seq中的值为键,并给所有键对应的值一个默认值

lichao = (”123“,”456“)
dict = dict.fromkeys(lichao)
print(dict)                 #结果为 {”123“:none , ”456“:none}

dict = dict.fromkeys(lichao,10)
                                # 结果为{”123“:10,”456“:10}

4.get 返回字典中的值  如果没有对应的key,返回默认值   小提示(用%s表示引用,%后写要引用的值)

dictionary = {“123”:"2",“456”:"3"}
print(dictionary.get("123"))
# 其值为2
dictionary = {
       “123”:“444”
       “456”:“798”

}
print  “value:%s“  %  dictionary.get("123")


#其结果为value:444

5.has key  查找字典中是否存在键 如果存在提示true 否则提示false

dictionary = {
              "123":"456",
              "ppp":"012"
             

}

print(dictionary.has_key("123"))

#其结果应为 true 

6.items 以列表返回可遍历的(键,值)元祖数组

dictionary = {

      ”123“:”11“,
      ”456“:”99“
}
print(dictionary.items())

#结果为[("123":"11"),("456":"99")]

7.keys  查找字典中所有键

dictionary = {
          ”123“:”11“,
          ”456“ :”22“


}
print(dictionary.keys())
#结果为[”123“,”456“]

8.setdefault  (放置一个未设置的值) 跟get类似,但如果没有找到key,则会创建一个key并赋值默认值,default=none

dictionary = {
         ”aa” = “123”
         “bb” = “456”  
}

y = dictionary.setdefault("www")
print(y)
#其结果为{“aa”:“123”,“bb”:“456”,“www”:none}

9.update  把字典2中的键值对更新到字典1中

dictionary = {
          “123”= “44”,
          “456”=“88”
 
}

dict2 = {
        "666":"sd"

}

dictionary.update(dict2)
print(dictionary)

#其结果为{“123”:“44”,“456”:88,“666”:”sd“}

10.values  返回字典中所有的值 

dictionary = {
          ”132“ :”55“ 

}

print(dictionary.values())

#其结果为 ["55"]

11.pop  删除一个键值对,并返回其值

dictionary = {
”213“:”44“,
”1515“:”12“

}
dictionary.pop("1515")
print(dictionary)

结果为:{"213":"44"}

12.popitems 随机删除字典当中的一个键值对

dict = {
       ”abc“:”456“,
         ”qwe”:“1212”


}
dict.popitems()

print(dict)

#结果为{‘123’:‘45’}

 其他

for循环

用户按照顺序循环可迭代对象中的内容:

list = ['11','22','33']
for i in list:
 print(i)

#结果为:‘11’  '22' '33'

PS 还有 if else break continue

 

enumrate  为可迭代的对象添加序号

list =  {”11“,”22“,”33“}
for index,item in enumrate(list):
print(index,item)

#输出为 (0,”11“)  (1,”22“) (2,”33“)

 

range 在指定范围生成数字 3.0中已经没有range 被xrange替代  xrange更省内存

list = range(0,10print(list)
#结果为1- 10

 

练习题:

一、元素分类

有如下值集合 [11,22,33,44,55,66,77,88,99,90...],将所有大于 66 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中。
即: {'k1': 大于66的所有值, 'k2': 小于66的所有值}

list =  [11,22,33,44,55,66,77,88,99,90]
dictionary = {
       "k1":[],
       "k2":[]  

}
for i in list:
       if i <66:
           dictionary["k1"].append(i)
       else:
           dictionary["k2"].append(i)
print(dictionary)

重点是要先创建一个空字典,然后利用循环取添加值,要提前设置一个空的值。

 
二、查找
查找列表中元素,移除每个元素的空格,并查找以 a或A开头 并且以 c 结尾的所有元素。
    li = ["alec", " aric", "Alex", "Tony", "rain"]
    tu = ("alec", " aric", "Alex", "Tony", "rain") 
    dic = {'k1': "alex", 'k2': ' aric',  "k3": "Alex", "k4": "Tony"}

 

posted @ 2017-06-11 18:38  杨sang  阅读(127)  评论(0)    收藏  举报