python基础数据类型

python常用的数据类型包括整型(int)、字符串(str)、布尔值(bool)、列表(list)、元组(tuple)、字典(dict)、集合(set)

整型(int)

int操作方法

bit_length()就是查看十进制数转换成二进制在内存中占用了多少长度

1 a = 5
2 print(a.bit_length())    # 当十进制用二进制表示时,最少使用的位数          3

int、bool、str三种转换

>>> i = 10       # int --> str
>>> str(i)
'10'
>>> ii = -1
>>> str(ii)
'-1'
>>> iii = 0
>>> str(iii)
'0'
>>> iiii = 000
>>> str(iiii)
'0'
 1 >>> s1 = '20'            # str --> int
 2 >>> int(s1)
 3 20
 4 >>> s2 = '0500'
 5 >>> int(s2)
 6 500
 7 >>> s3 = '-122'
 8 >>> int(s3)
 9 -122
10 >>>
1 >>> i = 5               # int --> bool
2 >>> bool(i)
3 True
4 >>> a = -1
5 >>> bool(a)
6 True
7 >>> b = 0
8 >>> bool(b)
9 False
>>> int(True)          # bool --> int
1
>>> int(False)
0
>>>
>>> s4 = 'hello'               # str --> bool
>>> bool(s4)
True
>>> s5 = ' '
>>> bool(s5)
True
>>> s6 = ''
>>> bool(s6)
False
1 >>> str(True)              # bool --> str
2 'True'
3 >>> str(False)
4 'False'

 字符串(str)

python中凡是使用引号引起来的数据可以称为字符串类型,组成字符串的每个元素称为字符。

组成字符串的字符元素从左到右依次排列,是有顺序的(从0开始)。对字符串进行索引,切片出来的数据都是字符串类型。

切片操作

 1 >>> s = 'python学习课程'
 2 >>> s1 = s[0]
 3 >>> s1
 4 'p'
 5 >>> type(s1)
 6 <class 'str'>
 7 >>> s2 = s[6]
 8 >>> s2
 9 ''
10 >>> s3 = s[-1]
11 >>> s3
12 ''
13 >>> s4 = s[0:6]
14 >>> s4
15 'python'
16 >>> s5 = s[:6]
17 >>> s5
18 'python'
19 >>> s6 = s[6:]
20 >>> s6
21 '学习课程'
22 >>> s7 = s[:8:2]               # 2 代表步长
23 >>> s7
24 'pto学'
25 >>> s8 = s[-1:-8]
26 >>> s8
27 ''
28 >>> s8 = s[-1:-8:-1]
29 >>> s8
30 '程课习学noh'
31 >>> s9 = s[:]
32 >>> s9
33 'python学习课程'
34 >>> s10 = s[-1:]
35 >>> s10
36 ''
View Code
 1 s = "123a4b5c"
 2 s1 = s[:3]
 3 print(s1)             # "123"
 4 s2 = s[3:6]
 5 print(s2)             #  "a4b"
 6 s3 = s[::2]
 7 print(s3)           # "1345"
 8 s4 = s[1:-2:2]
 9 print(s4)            # "2ab"
10 s5 = s[-1]
11 print(s5)           # "c"
12 s6 = s[-3::-2]
13 print(s6)        # "ba2"
View Code
  1 >>> s = "Turn right on this street."
  2 >>> s1 = s.upper()                                # 变大写
  3 >>> s1
  4 'TURN RIGHT ON THIS STREET.'
  5 >>> s2 = s.lower()                               # 变小写
  6 >>> s2
  7 'turn right on this street.'
  8 >>> s.count("r")
  9 3
 10 >>>
 11 >>> s.count("r", 0, 9)
 12 2
 13 >>> ss = "ascaljcdashc;LS"
 14 >>> ss
 15 'ascaljcdashc;LS'
 16 >>> ss.startswith("as")                # 以...开头
 17 True
 18 >>> ss.startswith("asd")
 19 False
 20 >>> ss.startswith("sw", 5, -1)         # 加了切片
 21 False
 22 >>> ss.startswith("jc", 5 , -1)
 23 True
 24 >>> ss.endswith("S")                     # 判断是否以...结尾
 25 True
 26 >>> ss.endswith("c", 6, 11)
 27 False
 28 >>> ss.endswith("c", 6, 12)
 29 True
 30 >>> s = "Hope has always been like a teenager, clean and pure peace of mind"
 31 >>> s.split()
 32 ['Hope', 'has', 'always', 'been', 'like', 'a', 'teenager,', 'clean', 'and', 'pure', 'peace', 'of', 'mind']
 33 
 34 >>> s.split(",")
 35 ['Hope has always been like a teenager', ' clean and pure peace of mind']
 36 
 37 >>> s1  = "name:alex:age:18:gender:male"
 38 >>> s1.split(":")
 39 ['name', 'alex', 'age', '18', 'gender', 'male']
 40 >>> s1.split(":",2)
 41 ['name', 'alex', 'age:18:gender:male']
 42 >>> s2 = " :tom:ethan:alex"
 43 >>> s2.split(":")
 44 [' ', 'tom', 'ethan', 'alex']
 45 >>> s3 = "alex"
 46 >>> "+".join(s3)
 47 'a+l+e+x'
 48 >>> type("+".join(s3))
 49 <class 'str'>
 50 >>> s4 = "name"
 51 >>> " ".join(s3, s4)
 52 Traceback (most recent call last):
 53   File "<stdin>", line 1, in <module>
 54 TypeError: join() takes exactly one argument (2 given)
 55 >>> ss = s.split()
 56 >>> ss
 57 ['Hope', 'has', 'always', 'been', 'like', 'a', 'teenager,', 'clean', 'and', 'pure', 'peace', 'of', 'mind']
 58 >>> " ".join(ss)
 59 'Hope has always been like a teenager, clean and pure peace of mind'
 60 
 61 >>> li = ["s", "a", "b", "f", 33]
 62 >>> type(li)
 63 <class 'list'>
 64 >>> "".join(li)
 65 Traceback (most recent call last):
 66   File "<stdin>", line 1, in <module>
 67 TypeError: sequence item 4: expected str instance, int found
 68 >>> s = "Hope has always been like a teenager, clean and pure peace of mind"
 69 >>> s.split()
 70 ['Hope', 'has', 'always', 'been', 'like', 'a', 'teenager,', 'clean', 'and', 'pure', 'peace', 'of', 'mind']
 71 >>>
 72 >>> s.split(",")
 73 ['Hope has always been like a teenager', ' clean and pure peace of mind']
 74 
 75 >>> s1  = "name:alex:age:18:gender:male"
 76 >>> s1.split(":")
 77 ['name', 'alex', 'age', '18', 'gender', 'male']
 78 >>> s1.split(":",2)
 79 ['name', 'alex', 'age:18:gender:male']
 80 >>> s2 = " :tom:ethan:alex"
 81 >>> s2.split(":")
 82 [' ', 'tom', 'ethan', 'alex']
 83 
 84 >>> s3 = "alex"
 85 >>> "+".join(s3)
 86 'a+l+e+x'
 87 >>> type("+".join(s3))
 88 <class 'str'>
 89 >>> s4 = "name"
 90 >>> " ".join(s3, s4)
 91 Traceback (most recent call last):
 92   File "<stdin>", line 1, in <module>
 93 TypeError: join() takes exactly one argument (2 given)
 94 >>> ss = s.split()
 95 >>> ss
 96 ['Hope', 'has', 'always', 'been', 'like', 'a', 'teenager,', 'clean', 'and', 'pure', 'peace', 'of', 'mind']
 97 >>> " ".join(ss)
 98 'Hope has always been like a teenager, clean and pure peace of mind'
 99 
100 >>> li = ["s", "a", "b", "f", 33]
101 >>> type(li)
102 <class 'list'>
103 >>> "".join(li)
104 Traceback (most recent call last):
105   File "<stdin>", line 1, in <module>
106 TypeError: sequence item 4: expected str instance, int found
107 >>> s= "    hello   "
108 >>> s.strip()                     # 去除空格
109 'hello'
110 >>> s5 = "as你好jhd"
111 >>> s5.strip("ajhsd")
112 '你好'
113 >>> s5.strip("ajhs")
114 '你好jhd'
115 >>> s6 = "as你r好jhd"
116 >>> s6.strip("ajhsd")
117 '你r好'
118 >>>
119 >>> "**barry*****".strip()
120 '**barry*****'
121 >>> "**barry****".strip("*")
122 'barry'
123 >>> "**barry****".lstrip("*")
124 'barry****'
125 >>> "**barry****".rstrip("*")
126 '**barry'
127 
128 >>> s = "他叫王麻子,今年25,目前就读于双一流高校,王麻子喜欢唱歌,班上的人都叫王麻子歌神"
129 >>> s.replace("王麻子","张三")
130 '他叫张三,今年25,目前就读于双一流高校,张三喜欢唱歌,班上的人都叫张三歌神'
131 >>> s.replace("王麻子","张三",2)
132 '他叫张三,今年25,目前就读于双一流高校,张三喜欢唱歌,班上的人都叫王麻子歌神'
133 >>> s.replace("王麻子","张三",1,,3)
134   File "<stdin>", line 1
135     s.replace("王麻子","张三",1,,3)
136                           ^
137 SyntaxError: invalid character in identifier
138 >>> s.find("双一流")               # 返回的找到的元素的索引,如果找不到返回-1
139 16
140 >>> s.find("25", 1, 10)
141 8
142 >>> s.find("哈哈")
143 -1
144 >>> ss = "tom123"
145 >>> ss.isalnum()         #字符串由字母或者数字组成
146 True
147 >>> ss.isalpha()             # 字符串只由字母组成
148 False
149 >>> ss.isdecimal()           # 字符串只由十进制组成
150 False
151 >>> ss.index("tom")            # 返回的找到的元素的索引,找不到报错
152 0
153 >>> ss.index("12")
154 3
155 >>> ss.index("12",3, 6)
156 3
View Code
1 s = "我叫{},今年{},毕业于{} ".format("alex", 25, "ynu")           # 我叫alex,今年25,毕业于ynu
2 s = "我叫{0},今年{1},毕业于{2}, {2}是一所双一流高校".format("alex", 25, "ynu")         # 我叫alex,今年25,毕业于ynu, ynu是一所双一流高校
3 s = "我叫{name},今年{age},毕业于{school}, {school}是一所双一流高校".format(name = "alex", age = 25, school = "ynu")     # 我叫alex,今年25,毕业于ynu, ynu是一所双一流高校
4 # print(s)
View Code
1 s = "if you are not satified with the life"
2 # print(s.capitalize())         #首字母大写                  # If you are not satified with the life
3 # print(s.swapcase())          #大小写翻转               # IF YOU ARE NOT SATIFIED WITH THE LIFE
4 s1 = "IF YOU ARE NOT SATIFIED WITH THE LIFE"
5 # print(s1.swapcase())                                     # if you are not satified with the life
6 print(s.title())                 #每个单词的首字母大写       # If You Are Not Satified With The Life
View Code

for循环

有限循环
for 变量 in iterable:
    pass


for...else...
for i in range(3):
    print(i)              #i:0,1,2

for j in range(1,10):     #1是起始位置
    print(j)              #j:1,2,3,4,5,6,7,8,9

for k in range(1,10,2):      #2是步长
    print(k)                #k:1,3,5,7,9

for m in range(100):
    if m < 50 or m > 70:
        print(m)                   # 输出0..49和71...99的int类型数

index = 0
while index < 13:
    print(index)              # 循环输出0

index = 0
while index < 13:
    print(index)              # 0...12
    index += 1

s = "第一行找规律,第二行验证规律,第三行使用规律"
# print(len(s))                            # 22
index = 0
while index < 22:              # 写成 index < 23 报IndexError: string index out of range
    # print(index)               # 0到21
    print(s[index])
    # print(s[index].join("sb"))
    print(s[index] + "sb")
    index += 1

s = "Don't let fear stop you from doing the thing you love"
li = []
for item in s.split():
    # print(item)             # Don't、let、...、you、love
    li.append(item)

# print(li)           # ["Don't", 'let', 'fear', 'stop', 'you', 'from', 'doing', 'the', 'thing', 'you', 'love']

dic = {"name" : "tom", "age" : 25, "gender" : "female"}
for k, v in dic.items():
    # print(k,v)            # name tom            age 25           gender female
    print(k)                # name  age  gender

for item in enumerate(li):          # 起始位置默认是0,可更改
    print(item)                   # (0, "Don't")、(1, 'let')、(2, 'fear')...、(10, 'love')


for index, name in enumerate(li, 100):          # 起始位置默认是0,可更改为100
    print(index, name)                   # (100, "Don't")、(101, 'let')、(102, 'fear')...、(110, 'love')
View Code

 

列表--list

 整型数字主要用于计算,bool值主要用于条件判断,字符串可以存储数据,但是只能存储少量的数据,对于大量的数据用字符串进行存储既不方便又不容易,且存储的数据类型只能是字符串类型。列表是一种可以承载多种数据类型的容器类数据类型,是python的基础数据类型之一,其他编程语言也有类似的数据类型.比如JS中的数组, java中的数组等等。列表相比于字符串,不仅可以储存多种不同的数据类型,而且可以储存大量的数据,列表是有序的,有索引值,可切片,方便取值。列表是可变的(mutable)----可改变列表的内容

列表的创建

# method 1
li = [33, 22, "tom", "hello", [11, "hey"], {"name": "alex", "age": 25} ]
print(li, type(li))            # [33, 22, 'tom', 'hello', [11, 'hey'], {'name': 'alex', 'age': 25}]    <class 'list'>

# method 2
lii = list()
print(lii, type(lii))               # []    <class 'list'>
liii = list("123")
print(liii, type(liii))        # ['1', '2', '3']    <class 'list'>


# method 3   列表推导式
lis = [i for i in range(1, 10, 2)]
print(lis, type(lis))              # [1, 3, 5, 7, 9]    <class 'list'>

列表的增删改查

 1 a = ["zcj", "zcc", "zls", "ldw", "ht"]
 2 
 3 #
 4 print(a)           # ['zcj', 'zcc', 'zls', 'ldw', 'ht']
 5 print(a[1])        # "zcc"
 6 print(a[2:])       # ['zls', 'ldw', 'ht']      从左到右取到最后                 切片
 7 print(a[1:3])      # ['zcc', 'zls']            从左往右取,左闭右开
 8 print(a[1:-1])      #  ['zcc', 'zls', 'ldw']
 9 print(a[1:-1:2])    # 2是步长,['zcc', 'ldw']
10 print(a[:3])         # ['zcj', 'zcc', 'zls']
11 print(a[1::2])       # ['zcc', 'ldw']
12 
13 # 以上都是从左往右取
14 
15 print(a[3::-1])      # 从右往左一个一个的取  ['ldw', 'zls', 'zcc', 'zcj']
16 print(a[-1::-2])       #从右往左隔一个取  ['ht', 'zls', 'zcj']
17 b = a[3::-1]
18 print(b)                  #  ['ldw', 'zls', 'zcc', 'zcj']
19 
20 # 添加 有两种方法:append, insert
21 
22 a.append("hhh")       # 默认添加到列表最后,即追加 ,给列表的最后面追加一个元素
23 print(a)              #  ['zcj', 'zcc', 'zls', 'ldw', 'ht', 'hhh']
24 
25 a.append(["hhh"])
26 print(a)               #   ['zcj', 'zcc', 'zls', 'ldw', 'ht', ['hhh']]
27 
28 a.append(["hhh","xxx"])   #   a.append("hhh","xxx") 会报错
29 print(a)                           # ['zcj', 'zcc', 'zls', 'ldw', 'ht', ['hhh', 'xxx']]
30 
31 
32 # extend方法修改了被扩展的列表,而原始的连接操作(+)则不然,它会返回一个全新的列表
33 a.extend(["hhh","xxx"])    # a.extend("hhh", "xxx")会报错
34 print(a)                           # ['zcj', 'zcc', 'zls', 'ldw', 'ht', 'hhh', 'xxx']
35 
36 a.extend("hhh")
37 print(a)                    #   ['zcj', 'zcc', 'zls', 'ldw', 'ht', 'h', 'h', 'h']
38 
39 a.extend(["hhh"])           # 扩展, 迭代着追加,在列表的最后面迭代着追加一组数据
40 print(a)                    #  ['zcj', 'zcc', 'zls', 'ldw', 'ht', 'hhh']
41 
42 a.insert(1,"hhh")             #  在序列下标为一的地方插入,在列表的任意位置插入元素                    insert(index, 内容)
43 print(a)                     #  ['zcj', 'hhh', 'zcc', 'zls', 'ldw', 'ht']
44 
45 
46 # 修改
47 
48 a[1] = "jjj"
49 print(a)                # ['zcj', 'jjj', 'zls', 'ldw', 'ht']
50 
51 a[1:3] = ["hhh", "xxx"]
52 print(a)                 #  ['zcj', 'hhh', 'xxx', 'ldw', 'ht']
53 l = ['太白', 'alex', 'WuSir', '女神']
54 l[1:3] = 'abcdefg'
55 print(l) # ['太白', 'a', 'b', 'c', 'd', 'e', 'f', 'g', '女神'] 
56 
57 # 按照切片(步长)改值(必须一一对应)
58 l = ['太白', 'alex', 'WuSir', '女神']
59 l[::2] = '对应'
60 print(l) # ['对', 'alex', '应', '女神']
61 
62 #删除  有三种:remove,pop,del
63 
64 a.remove("zcj")      # remove不能删除切片形式的  通过元素删除列表中该元素,如果有重名元素,则默认删除从左到右的第一个元素
65 a.remove(a[0])
66 print(a)                  # ['zcc', 'zls', 'ldw', 'ht']
67 
68 b = a.remove("zcj")
69 print(a)          #  ['zcc', 'zls', 'ldw', 'ht']
70 print(b)          #  None
71 
72 b = a.pop(0)         # 通过索引删除列表中对应的元素,该方法有返回值,返回值为删除的元素
73 print(a)             #  ['zcc', 'zls', 'ldw', 'ht']
74 print(b)            #  zcj
75 
76 a.pop()              #  默认删除最后一个
77 print(a)               # ['zcj', 'zcc', 'zls', 'ldw']
78 
79 del a[0]            #  按照索引删除该元素   ['zcc', 'zls', 'ldw', 'ht']
80 print(a)
81 
82 del a            # 删除整个列表
83 print(a)
84 
85 a.clear()   # 清空
86 print(a)         # []
View Code

补充

 1 #count
 2 a = ["to", "be", "not", "to", "be"]
 3 print(a.count("to"))               # 输出2, count统计某个元素在列表中出现的次数
 4 
 5 a = [1, 2 ,3]
 6 b = [4, 5, 6]
 7 #a.extend(b)
 8 # print(a)                    #    [1, 2, 3, 4, 5, 6]
 9 # print(b)                    #   [4, 5, 6]
10 # print(a + b)                 # [1, 2, 3, 4, 5, 6]
11 print(a * 3)                 # [1, 2, 3, 1, 2, 3, 1, 2, 3]
12 
13 #index  根据内容找其对应的位置
14 a = ["zcj", "zcc", "zls", "ldw", "ht"]
15 print(a.index("zcc"))           # 输出1      假如列表中存在相同的几个值,那么index取的是第一个
16 
17 a = ["zcj", "zcc", "ht", "zls", "ldw", "ht"]
18 # print(a.index("ht"))             # 输出2
19 
20 first_ht_index = a.index("ht")               # 获取列表中第一个ht
21 print("first_ht_index:", first_ht_index)            #  输出2
22 
23 little_list = a[first_ht_index + 1:]          # 切片,切出从列表第一个ht后的一个元素到最后一个元素的子列表
24 
25 sencond_ht_index = little_list.index("ht")
26 print("sencond_ht_index", sencond_ht_index)        #  输出2
27 
28 second_ht_in_a_list = first_ht_index + sencond_ht_index + 1
29 print("second_ht_in_a_list", second_ht_in_a_list)           #  输出5
30 print(a[second_ht_in_a_list])                       # 输出ht
31 
32 # reverse 倒置
33 a = ["zcj", "zcc", "ht", "zls", "ldw", "ht"]
34 a.reverse()
35 print(a)            # 输出 ['ht', 'ldw', 'zls', 'ht', 'zcc', 'zcj']
36 
37 # sort 排序
38 a = [2, 8, 3, 5, 7]
39 a.sort(reverse = True)               #  从大到小排序  [8, 7, 5, 3, 2]
40 a.sort(reverse = False)                 # 从小到大排序  [2, 3, 5, 7, 8],    a.sort()默认从小到大
41 sorted(a)
42 print(a)                               # [2, 8, 3, 5, 7]
43 
44 b = ["zcj", "zcc", "ht", "zls", "ldw", "ht"]
45 print("ccc" in b)        # "ccc"不在b中,故返回False
46 b.sort()                 #  根据ASCII来排序
47 print(b)                    # ['ht', 'ht', 'ldw', 'zcc', 'zcj', 'zls']
48 
49 a = [2, 8, 3, 5, 7]
50 print(a is list)              # 输出False
51 print(type(a) is list)         # 输出True
View Code

 列表嵌套

 1 ""
 2 l1 = [1, 2, 'tom', [1, 'alex', 3,]]
 3 1, 将l1中的'tom'变成大写并放回原处。
 4 2,给小列表[1,'alex',3,]追加一个元素,'老男孩教育' 5 3,将列表中的'alex'通过字符串拼接的方式在列表中变成'alexsb'
 6 """
 7 
 8 l1 = [1, 2, 'tom', [1, 'alex', 3,]]
 9 
10 #l1[2] = "TOM"
11 1[2] = l1[2].upper()
12 print(l1)                    # [1, 2, 'TOM', [1, 'alex', 3]]
13 
14 l1[3] = [1, 'alex', 3, "老男孩教育"]
15 print(l1)                             # [1, 2, 'tom', [1, 'alex', 3, '老男孩教育']]
16 
17 l1[3] = l1[3] + ["老男孩教育"]
18 print(l1[3])                  # [1, 'alex', 3, '老男孩教育']
19 print(l1)                 # [1, 2, 'tom', [1, 'alex', 3, '老男孩教育']]
20 
21 l1[-1].append("老男孩教育")
22 print(l1[-1])                     # [1, 'alex', 3, '老男孩教育']
23 print(l1)                         # [1, 2, 'tom', [1, 'alex', 3, '老男孩教育']]
24 
25 print(l1[-1][1])               # alex
26 print(l1[-1][1] + "sb")          # alexsb
27 #l1[-1][1] = "alexsb"
28 l1[-1][1] = l1[-1][1] + "sb"
29 print(l1)                       # [1, 2, 'tom', [1, 'alexsb', 3]]
View Code

元组--tuple

 元组:俗称不可变的列表,又被成为只读列表,元祖也是python的基本数据类型之一,用小括号括起来,里面可以存放任何数据类型的数据,查询可以,循环也可以,切片也可以.但就是不能改.

 1 # tup1 = ()    # 空元组
 2 # tup2 = (2,)   #包含一个元素的元组
 3 
 4 a = (11, 22, 33, 44, 55)
 5 print(a[1])                 # 22
 6 print(a[1:3])               #  (22, 33)
 7 
 8 b = (11, "reality", True, [11, "stop", False, 5])
 9 for item in b:               # 查看
10     print(item)
11 
12 print(b[-1])           # [11, 'stop', False, 5]
13 b[-1].append(2)
14 print(b)                 # (11, 'reality', True, [11, 'stop', False, 5, 2])
15 print(b.index(True))       # 2      通过元素找索引(可切片),找到第一个元素就返回,找不到该元素即报错。
16 
17 print(b.count(11))          # 1     获取某元素在列表中出现的次数
View Code
1 a, b = (1, 10)          # 元组的拆包,必须一一对应,列表也可以拆包,但主要以元组拆包为主
2 print(a)           # 1
3 print(b)            # 10

练习

1 li = range(5)
2 print(li[1: 3])             # range(1, 3)
3 print(li[-1])                  # 4
4 
5 for i in range(1, 5, -1):
6     print(i)                   # 没输出
View Code
 1 实现一个整数加法计算器(多个数相加)
 2 如:content = input("输入内容:"), 用户输入5 +9+6 +12+  13
 3 
 4 content = input("请输入内容:")
 5 li = content.split("+")
 6 # print(li)
 7 sum = 0
 8 for i in li:
 9     # print(int(i))
10     sum += int(i)
11 
12 print(sum)                      # 45
View Code
计算用户输入的内容中有几个整数(以个位数为单位)
如 content = input("输入内容:"),如acwav1234dvcqww4dcvr6-*9

content = input("请输入内容:")
count = 0
for i in content:
    # print(i, type(i))            # 类型全是str
    if i.isdecimal():
        count += 1
print(count)                 # 7
View Code
 1 #判断一句话是否是回文。 回文:正着念和反着念都一样,比如:上海自来水来自海上
 2 
 3 # st = "今天天气不错!"
 4 # print(st[:])                       # 今天天气不错!
 5 # print(st[-1::-1])                  # !错不气天天今
 6 content = input("请输入内容:")
 7 if content == content[-1::-1]:
 8     print("它是回文")
 9 else:
10     print("它不是")
View Code
 1 # li = [1, "d", 4, 5, "c"]
 2 # print(li[-1])             # c
 3 # print(li[-1:])           # ['c']
 4 
 5 li = ["alex", "tom", "ethan"]
 6 # print("_".join(li))                  # alex_tom_ethan
 7 s = ""
 8 for i in li:
 9     s = s + "_" + i
10 print(s)                              # _alex_tom_ethan
11 print(s[1:])                          # alex_tom_ethan
View Code

字典--dict

 鉴于列表可以存储大量的数据类型,但是如果数据量大的话,他的查询速度比较慢;列表只能按照顺序存储,数据与数据之间关联性不强。引入另一种容器型的数据类型,解决前文所述的问题-----字典dict.

数据类型的分类:

    可变(不可哈希)的数据类型:list、dict、set

    不可变(可哈希)的数据类型:int、bool、str、tuple                # 这里的不可变指的是对原对象没有改变,改变形成的是新对象

1 s = "alex"                   # 不可变
2 s2 = s.upper()
3 print(s, s2)                # alex ALEX
4 
5 l1 = [1, 2]                   # 可变
6 l1.append(3)
7 print(l1)                    # [1, 2, 3]
View Code

字典:{}表示,以键值对形式存储的容器型数据类型

1 dic = {
2     "王麻子": {"name": "王麻子", "age": 15, "gender": "male"},
3     "python学习班": ["李四", "张三", "张帆", "王府井"]
4 }
View Code

Key: 不可变(可哈希)的数据类型.并且键是唯一的,不重复的。

Value:任意数据(int,str,bool,tuple,list,dict,set),包括后面要学的实例对象等。

在Python3.5版本(包括此版本)之前,字典是无序的。

在Python3.6版本之后,字典会按照初建字典时的顺序排列(即第一次插入数据的顺序排序)。

字典的查询速度快,存储关联性的数据。出现以空间换时间的缺点

字典的创建

# method1
dic1 = dict()
print(dic1)                   # {}

dic2 = dict( (("one", 1), ("two", 2), ("three", 3)) )
print(dic2)                                             # {'one': 1, 'two': 2, 'three': 3}

dic3 = dict([("age", 18), (("name", "alex"))])
print(dic3)                                               # {'age': 18, 'name': 'alex'}

# method2
dic4 = dict(name = "alex", age = 19, one = 1)
print(dic4)                                             # {'name': 'alex', 'age': 19, 'one': 1}

# meyhod3
dic5 = dict({"name": "tom", "age": 15, "two":2})
print(dic5)                                               # {'name': 'tom', 'age': 15, 'two': 2}

# method 4
dic6 = dict(zip(("name", 123, True, (1, 11)), ("ALEX", 456, "HH", "hello")))
print(dic6)                                             # {'name': 'ALEX', 123: 456, True: 'HH', (1, 11): 'hello'}

dic7 = dict(zip(["name", 123, True, (1, 11)], ["ALEX", 456, "HH", "hello"]))
print(dic7)                                             # {'name': 'ALEX', 123: 456, True: 'HH', (1, 11): 'hello'}

# method 5
dic8 = {k: v for k, v in [("one", 1), ("name", "alex"), ("age", 18)]}
print(dic8)                                                # {'one': 1, 'name': 'alex', 'age': 18}

dic9 = {k: v for k, v in (("one", 1), ("name", "alex"), ("age", 18))}
print(dic9)                                # {'one': 1, 'name': 'alex', 'age': 18}

# method 6
dic11 = dict.fromkeys("alex", 1234)
print(dic11)                               # {'a': 1234, 'l': 1234, 'e': 1234, 'x': 1234}
View Code
 1 dic = {123: 456, True: 999, "id": 1, "name": 'sylar', "age": 18, "stu": ['帅哥', '美⼥'], (1, 2, 3): '麻花藤'}
 2 print(dic[123])                  # 456
 3 print(dic[True])                 # 999
 4 print(dic['id'])                 # 1
 5 print(dic['stu'])                  # ['帅哥', '美⼥']
 6 print(dic[(1, 2, 3)])           # 麻花藤
 7 
 8 # 不合法
 9 # dic = {[1, 2, 3]: '周杰伦'}    # list是可变的. 不能作为key
10 # dic = {{1: 2}: "哈哈哈"}       # dict是可变的. 不能作为key
11 dic = {{1, 2, 3}: '呵呵呵'}         # set是可变的, 不能作为key      TypeError: unhashable type: 'set'
View Code

字典的常用操作

#   增删改查
dic = dict({"name": "alex", "age": 25, "gender": "male"})
# print(dic, type(dic))                                    # {'name': 'alex', 'age': 25, 'gender': 'male'}     <class 'dict'>

#
# dic["hobby"] = "football"
# print(dic)                                             # {'name': 'alex', 'age': 25, 'gender': 'male', 'hobby': 'football'}
# dic["age"] = 19
# print(dic)                                             # {'name': 'alex', 'age': 19, 'gender': 'male'}
# dic.setdefault(123, 456)                                 # {'name': 'alex', 'age': 25, 'gender': 'male', 123: 456}
dic.setdefault("school", "ynu")                          # {'name': 'alex', 'age': 25, 'gender': 'male', 'school': 'ynu'}
dic.setdefault("age", 21)                                # {'name': 'alex', 'age': 25, 'gender': 'male', 'school': 'ynu'}   并未发生改变
ret = dic.setdefault("weight", 60)
# print(dic)
# print(ret)                                                # 60         有返回值

#
# res = dic.pop("gender")
# print(dic)                                         # {'name': 'alex', 'age': 25}
# print(res)                                         # male
# res = dic.pop("height")
# print(dic)                                           # 报错   KeyError: 'height'
# res = dic.pop("height", "没有该项")
# print(dic)                                           # {'name': 'alex', 'age': 25, 'gender': 'male'}
# print(res)                                           # 没有该项
# dic.popitem()                                       # 默认删除最后一项
# print(dic)                                         # {'name': 'alex', 'age': 25}
# dic.clear()                                          # 清空
# print(dic)                                           # {}
# del dic["gender"]                                     # {'name': 'alex', 'age': 25}
# del dic                                             #  删除整个字典   NameError: name 'dic' is not defined

#
# dic["name"] = "tom"                                       # {'name': 'tom', 'age': 25, 'gender': 'male'}
# dic.update(gender = "female", weight = 65)                  # {'name': 'alex', 'age': 25, 'gender': 'female', 'weight': 65}
# dic.update([("one", 1), ("two", 2)])                         # {'name': 'alex', 'age': 25, 'gender': 'male', 'one': 1, 'two': 2}
# dic.update((("one", 1), ("two", 2)))                        # {'name': 'alex', 'age': 25, 'gender': 'male', 'one': 1, 'two': 2}
dic1 = dict(zip((123, 456), (111, 789)))                    # {123: 111, 456: 789}
dic.update(dic1)
print(dic1)                                                 # {123: 111, 456: 789}
print(dic)                                                  #  {'name': 'alex', 'age': 25, 'gender': 'male', 123: 111, 456: 789}

#
# print(dic["name"])                   # alex
# print(dic.get("age"))                # 25
# print(dic.get("weight"))              # None
# print(dic.get("hobby", "girl"))       # girl

# d1 = dic.keys()
# print(d1, type(d1))                              # dict_keys(['name', 'age', 'gender'])      <class 'dict_keys'>
# print(list(d1), type(list(d1)))                     # ['name', 'age', 'gender']        <class 'list'>
# for item in dic.keys():
#     print(item)                                    # name       age       gender
# for item in dic:
#     print(item)                                    # name       age       gender

# d2 = dic.values()
# print(d2)                      # dict_values(['alex', 25, 'male'])
# print(list(d2))                  # ['alex', 25, 'male']
# for i in dic.values():
#     print(i)                     # alex   25    male

# d3 = dic.items()
#print(d3, type(d3))            # dict_items([('name', 'alex'), ('age', 25), ('gender', 'male')])         <class 'dict_items'>
# print(list(d3))                 #  [('name', 'alex'), ('age', 25), ('gender', 'male')]
# for i in dic.items():
#     print(i)                      # ('name', 'alex')    ('age', 25)     ('gender', 'male')
# for k ,v in dic.items():
#     print(k, v)                     # name alex         age 25            gender male
View Code
1 dd = dict.fromkeys("你好", "师姐")
2 ddd = dict.fromkeys([1, "done", True], "嗯哼")
3 print(dd)                                # {'你': '师姐', '好': '师姐'}
4 print(ddd)                               # {1: '嗯哼', 'done': '嗯哼'}
View Code

练习题

"""
dic = {'k1': "v1", "k2": "v2", "k3": [11,22,33]}
请在字典中添加一个键值对,"k4": "v4",输出添加后的字典
请在修改字典中 "k1" 对应的值为 "alex",输出修改后的字典
请在k3对应的值中追加一个元素 44,输出修改后的字典
请在k3对应的值的第 1 个位置插入个元素 18,输出修改后的字典
"""

dic1 = {"k1": "v1", "k2": "v2", "k3": [11, 22, 33]}
# dic1["k4"] = "v4"
# dic1.setdefault("k4", "v4")
# print(dic1)                                                      # {'k1': 'v1', 'k2': 'v2', 'k3': [11, 22, 33], 'k4': 'v4'}

# dic1["k1"] = "alex"
# dic1.update(k1 = "alex")
# print(dic1)                                                   # {'k1': 'alex', 'k2': 'v2', 'k3': [11, 22, 33]}

# print(dic1["k3"])                                       # [11, 22, 33]
# dic1["k3"].append(44)
# print(dic1)                                                # {'k1': 'v1', 'k2': 'v2', 'k3': [11, 22, 33, 44]}
dic1["k3"].insert(0, 18)
print(dic1)                                            # {'k1': 'v1', 'k2': 'v2', 'k3': [18, 11, 22, 33]}
View Code

 字典嵌套

dic = {
    'name': '汪峰',
    'age': 48,
    'wife': [{'name':'国际章','age':38}],
    'children': {'girl_first': '小苹果', 'girl_second': '小怡', 'girl_three': '顶顶'}
}
# 1. 获取汪峰的名字。
# 2.获取这个字典:{'name':'国际章','age':38}。
# 3. 获取汪峰妻子的名字。
# 4. 获取汪峰的第三个孩子名字。

# 第一题
# ans1 = dic["name"]
# ans1 = dic.get("name")
# print(ans1)

# 第二题
# ans2 = dic.get("wife")
# print(ans2, type(ans2))                    # [{'name': '国际章', 'age': 38}]     <class 'list'>
# print(ans2[0])

# print(dic["wife"][0])                        # {'name': '国际章', 'age': 38}

# 第三题
# print(dic.get("wife")[0].get("name"))
# print(dic["wife"][0]["name"])

# 第四题
# print(dic["children"]["girl_three"])
print(dic.get("children").get("girl_three"))
View Code
dic2 = {
 'name':['alex',2,3,5],
 'job':'teacher',
 'oldboy':{'alex':['python1','python2',100]}
 }
1,将name对应的列表追加⼀个元素’wusir’。
2,将name对应的列表中的alex⾸字⺟⼤写。
3,oldboy对应的字典加⼀个键值对’⽼男孩’,’linux’。
4,将oldboy对应的字典中的alex对应的列表中的python2删除

# 第一题
# dic2["name"].append("wusir")
# print(dic2)

# dic2.get("name").append("wusir")
# print(dic2)

# 第二题
# print(dic2["name"][0].capitalize())                                  # Alex
# dic2["name"][0] = dic2["name"][0].capitalize()
# print(dic2)

# 第三题
# dic2.get("oldboy").update(老男孩 = "linux")
# dic2["oldboy"]["⽼男孩"] = "linux"
# print(dic2)

# 第四题
# dic2["oldboy"]["alex"].pop(1)
# dic2.get("oldboy").get("alex").remove("python2")
dic2.get("oldboy").get("alex").remove("python2")
print(dic2)
View Code

 作业练习

 1 # 查找列表li中的元素,移除每个元素的空格,并找出以"A"或者"a"开头,并以"c"结尾的所有元素,并添加到一个新列表中,最后循环打印这个新列表
 2 li = ["Taibai ", "alexc", "AbC ", "egon", " riTiAn", "WuSir", " aqc"]
 3 
 4 l1 = []
 5 for item in li:
 6     # print(item.strip())
 7     item = item.strip()                             # 去除空格
 8     # if (item.startswith("a") or item.startswith("A")) and item.endswith("c"):                 # 判断方法1 注意这里有优先级,( ) > not > and > or
 9     if item[0].upper() == "A" and item[-1] == "c":                                             # 判断方法2
10         # print(item)
11         l1.append(item)
12 
13 # print(l1)
14 for i in l1:
15     print(i)
View Code
# 开发敏感词过滤程序,提示用户输入评论内容。如果用户输入的内容中包含特殊的字符,
# 敏感词汇表 li = ["苍老师", "京东热", "武藤兰", "波多野结衣"]
# 则将用户输入的内容的敏感词替换成等长度的*(苍老师替换成***),
# 并添加到一个列表中;如果用户输入的内容没有敏感词汇则直接添加到上述的列表中

li = ["苍老师", "京东热", "武藤兰", "波多野结衣"]

L1 = []
comment = input("请输入评论内容:")                 # acsavwv京东热cfebe你好苍老师嗯哼dsa波多野结衣酷哈哈dawdvv武藤兰
for word in li:
    # print(word)
    if word in comment:
        # com = comment.replace(word, "*" * len(word))
        # print(com)                                   # 第一次循环:acsavwv京东热cfebe你好***嗯哼dsa波多野结衣酷哈哈dawdvv武藤兰
        #                                              # 第二次:acsavwv***cfebe你好苍老师嗯哼dsa波多野结衣酷哈哈dawdvv武藤兰
        #                                              # 第三次: acsavwv京东热cfebe你好苍老师嗯哼dsa波多野结衣酷哈哈dawdvv***
        #                                              # 第四次: acsavwv京东热cfebe你好苍老师嗯哼dsa*****酷哈哈dawdvv武藤兰
        comment = comment.replace(word, "*" * len(word))
        # print(comment)
L1.append(comment)
print(L1)
View Code
# 有如下列表
Li = [1, 3, 4, "alex", [3, 7, 8, "TaiBai"], 5, "RiTian"]
# 循环打印列表中的每个元素,遇到列表则再循环打印出它里面的元素
for item in Li:
    # print(item)
    if type(item) is list:
        for i in item:
            print(i)
    else:
        print(item)
View Code
users = ["李少奇", "李启航", 666, "渣渣辉"]
#请用"_"将它们连接起来

# users[2] = "666"
# print("_".join(users))             # 李少奇_李启航_666_渣渣辉

# s = ""                              # 相当于 count = 0
# for item in users:
#     s = s + "_" + str(item)
# s = s[1:]
# print(s)

s = ""
for index in range(len(users)):
    if index == 0:
        s = s + str(users[index])
    else:
        s = s + "_" + str(users[index])
print(s)
View Code
#请将元组 v1 = (11, 22, 33)中的所有元素追加到列表 v2 = [44, 55, 66]中
v1 = (11, 22, 33)
v2 = [44, 55, 66]

# a, b, c = v1
# print(a)              # 11
# v2.append(a)
# v2.append(b)
# v2.append(c)
# print(v2)

# for i in v1:
#     v2.append(i)
# print(v2)

v2.extend(v1)
print(v2)
View Code
# 请将元组 v1 = (11, 22, 33, 44, 55, 66, 77, 88, 99)中的所有偶数索引位置的元素追加到列表 v2 = [44, 55, 66]
v1 = (11, 22, 33, 44, 55, 66, 77, 88, 99)
v2 = [44, 55, 66]
print(v1[::2])                          # (11, 33, 55, 77, 99)
v2.extend(v1[::2])
print(v2)                               # [44, 55, 66, 11, 33, 55, 77, 99]
View Code
#将字典的键和值分别追加到key_list和value_list两个列表
info = {"k1": "v1", "k2": "v2", "k3": [11, 22, 33]}
# print(info.keys())                                   # dict_keys(['k1', 'k2', 'k3'])
key_list = []
value_list = []
keys = list(info.keys())
key_list.extend(keys)
print(key_list)
values = list(info.values())
value_list.extend(values)
print(value_list)
View Code
# 有字符串 "k: 1|k1: 2|k2: 3|k3: 4"处理成字典{"k": 1, "k1": 2...}
s = "k: 1|k1: 2|k2: 3|k3: 4"
s = s.split("|")
# print(s)                        # ['k: 1', 'k1: 2', 'k2: 3', 'k3: 4']
dic = dict()
for item in s:
    key, value = item.split(":")
    # print(key, value, type(key), type(value))                     # k  1 <class 'str'> <class 'str'> ...   k3  4 <class 'str'> <class 'str'>
    dic[key.strip()] = int(value)

print(dic)
View Code

集合--set

集合是无序的不重复的数据集合,它里面的元素是可哈希的(不可变类型),但是集合本身是不可哈希(所以集合做不了字典的键)的。以下是集合最重要的两点:

  去重,把一个列表变成集合,就自动去重了。

  关系测试,测试两组数据之前的交集、差集、并集等关系。

集合的创建

# 集合的创建
se = set({1, 2 , "tom"})
print(se, type(se))                   # {'tom', 1, 2} <class 'set'>

se1 = {1, 5, "嗯哼"}
print(se1, type(se1))                # {1, '嗯哼', 5} <class 'set'>

se2 = {1, [1, 2], (1, "你哈"), "sss"}             # 报错, TypeError: unhashable type: 'list'
print(se2, type(se2))

se2 = {1, (1, "你哈"), "sss"}             # {1, (1, '你哈'), 'sss'} <class 'set'>
print(se2, type(se2))

# 空集合、空字典
print({}, type({}))                            # {} <class 'dict'>
print(set(), type(set()))                     # set() <class 'set'>
View Code

集合增删

set1 = {'alex', 'wusir', 'ritian', 'egon', 'barry', "八戒"}
# 增加
# set1.add("黄忠")
# print(set1)                   # {'黄忠', 'ritian', 'barry', 'egon', 'wusir', '八戒', 'alex'}

# update 迭代着增加
# set1.update("safas")          # {'ritian', 'a', '八戒', 'wusir', 's', 'f', 'barry', 'alex', 'egon'}
# set1.update("你")               # {'ritian', '八戒', 'barry', 'wusir', 'egon', '你', 'alex'}
# set1.update("你好")            # {'barry', 'wusir', '八戒', '好', '你', 'alex', 'ritian', 'egon'}
# set1.update([1, 2, 3])         # {1, '八戒', 2, 3, 'alex', 'wusir', 'ritian', 'barry', 'egon'}
# print(set1)

# 删除
# set1.remove("alex")           # {'ritian', 'egon', 'wusir', 'barry', '八戒'}
# set1.pop()                       # 随机删除一个元素
# set1.pop(1)                      # TypeError: pop() takes no arguments (1 given)
# set1.clear()                   # 清空集合
# del set1                      # 删除整个集合
# print(set1)

# 变相改值
# set1.remove("八戒")
# set1.add("悟空")
# print(set1)                   # {'wusir', 'barry', '悟空', 'egon', 'ritian', 'alex'}
View Code

集合的其他操作

# 集合的其他操作
set2 = {1, 2, 3, 4, 5}
set3 = {4, 5, 6, 7, 8}

# 交集   & 或者 intersection
# print(set2 & set3)                 # {4, 5}
# print(set2.intersection(set3))        # {4, 5}

# 并集   | 或者 union
# print(set2 | set3)                # {1, 2, 3, 4, 5, 6, 7, 8}
# print(set2.union(set3))            # {1, 2, 3, 4, 5, 6, 7, 8}


# 差集  - 或者 difference
# print(set2 - set3)                 # {1, 2, 3}
# print(set2.difference(set3))        # {1, 2, 3}

# 反交集   ^ 或者 symmetric_difference
# print(set2 ^ set3)                         # {1, 2, 3, 6, 7, 8}
# print(set2.symmetric_difference(set3))        # {1, 2, 3, 6, 7, 8}
View Code

集合的子集和超集

set4 = {1, 2, 3}
set5 = {1, 2, 3, 4, 5, 6}
set6 = {1, 2, 3, 10}

# 子集
# print(set4 < set5)           # True
# print(set4.issubset(set5))     # True
# print(set6 < set5)           # False

# 超集
# print(set5 > set4)               # True
# print(set5.issuperset(set4))     # True


# 列表的去重
# l1 = [1, 1, 1, 2, 2, 4, 5, 5, 6, 7, 7, 10, 10]
# se = set(l1)                # {1, 2, 4, 5, 6, 7, 10}
# li = list(se)               # [1, 2, 4, 5, 6, 7, 10]
# print(li)
View Code

frozenset不可变集合,让集合变成不可变类型

# frozenset不可变集合,让集合变成不可变类型
a = frozenset("你好")
print(a, type(a))                  # frozenset({'你', '好'})             <class 'frozenset'>
b = frozenset('barry')             # frozenset({'r', 'b', 'a', 'y'})           <class 'frozenset'>
print(b, type(b))
View Code

 

posted @ 2020-07-22 17:23  Ethan272  阅读(144)  评论(0编辑  收藏  举报