引子
| 数据类型是用来记录事物状态的,而事物的状态是不断变化的(如:一个人年龄的增长(操作int类型) ,单个人名的修改(操作str类型),学生列表中增加学生(操作list类型)等),这意味着我们在开发程序时需要频繁对数据进行操作,为了提升我们的开发效率, python针对这些常用的操作,为每一种数据类型内置了一系列方法。本章的主题就是带大家详细了解下它们,以及每种数据类型的详细定义、类型转换。 |
数字类型(int与float)

定义
类型转换
| |
| |
| s = '123' |
| res = int(s) |
| print(res,type(res)) |
| print(int('12.3')) |
| Traceback (most recent call last): |
| File "<stdin>", line 1, in <module> |
| ValueError: invalid literal for int() with base 10: '12.3' |
| |
| |
| |
| print(bin(3)) |
| '0b11' |
| print(oct(9)) |
| '0o11' |
| print(hex(17)) |
| '0x11' |
| |
| print(int('0b11',2)) |
| print(int('0o11',8)) |
| print(int('0x11',16)) |
| |
| |
| s = '12.3' |
| res=float(s) |
| print(res,type(res)) |
| (12.3, <class 'float'>) |
内置方法(int)(了解操作)
| int.bit_length() |
| |
| - 返回整数的二进制表示中最高位的位数,不包括符号和前导零。 |
| num = 42 |
| bit_length = num.bit_length() |
| print(bit_length) |
| |
| ``` |
| |
| int.to_bytes(length, byteorder, signed) |
| |
| - 将整数转换为字节数组。 |
| - 参数`length`指定生成的字节数组的长度,`byteorder`指定字节顺序,`signed`指定是否考虑整数的符号。 |
| num = 42 |
| byte_array = num.to_bytes(2, byteorder='big', signed=False) |
| print(byte_array) |
| |
| ``` |
| |
| int.from_bytes(bytes, byteorder, signed) |
| |
| - 将字节数组转换为整数。 |
| - 参数`bytes`是输入的字节数组,`byteorder`指定字节顺序,`signed`指定是否考虑整数的符号。 |
| byte_array = b'\x00*' |
| num = int.from_bytes(byte_array, byteorder='big', signed=False) |
| print(num) |
| |
| ``` |
| |
| int.__add__(other) |
| |
| - 实现整数的加法运算。 |
| num1 = 42 |
| num2 = 10 |
| result = num1.__add__(num2) |
| print(result) |
| |
| ``` |
| |
| int.__sub__(other) |
| |
| - 实现整数的减法运算。 |
| num1 = 42 |
| num2 = 10 |
| result = num1.__sub__(num2) |
| print(result) |
| |
| ``` |
| |
| int.__mul__(other) |
| |
| - 实现整数的乘法运算。 |
| num1 = 42 |
| num2 = 10 |
| result = num1.__mul__(num2) |
| print(result) |
| |
| ``` |
| |
| int.__truediv__(other) |
| |
| - 实现整数的真除法运算。 |
| num1 = 42 |
| num2 = 10 |
| result = num1.__truediv__(num2) |
| print(result) |
| |
| ``` |
| |
| int.__floordiv__(other) |
| |
| - 实现整数的整除法运算。 |
| num1 = 42 |
| num2 = 10 |
| result = num1.__floordiv__(num2) |
| print(result) |
| |
| ``` |
| |
| int.__mod__(other) |
| |
| - 实现整数的取模运算。 |
| num1 = 42 |
| num2 = 10 |
| result = num1.__mod__(num2) |
| print(result) |
| |
| ``` |
| |
| int.__pow__(other, modulo=None) |
| |
| - 实现整数的幂运算。 |
| num1 = 2 |
| num2 = 3 |
| result = num1.__pow__(num2) |
| print(result) |
| |
内置方法(float)(了解操作)
| - 浮点类型的内置方法包括各种数学运算,例如加法、减法、乘法和除法。 |
| - 此外,还有一些与浮点数相关的函数,如取整函数 round()。 |
| |
| result_add = 3.14 + 2.5 |
| |
| |
| result_subtract = 5.7 - 1.2 |
| |
| |
| result_multiply = 2.0 * 3.5 |
| |
| |
| result_divide = 8.0 / 4.0 |
| |
| |
| rounded_number = round(3.14159) |
| - 这些方法和运算符都可用于浮点数的处理。值得注意的是,由于计算机存储浮点数的方式,可能存在一些精度问题。 |
补充:判断数字类型
数字类型说明
| num1 = b'4' |
| num2 = '4' |
| num3 = '四' |
| num4 = 'Ⅳ' |
1. 判断数字类型(isdigit)
| |
| print(num1.isdigit()) |
| print(num2.isdigit()) |
| print(num3.isdigit()) |
| print(num4.isdigit()) |
2.判断小数类型(isdecimal)
| |
| print(num2.isdecimal()) |
| print(num3.isdecimal()) |
| print(num4.isdecimal()) |
3.判断数字类型(isnumeric)
| |
| print(num2.isnumeric()) |
| print(num3.isnumeric()) |
| print(num4.isnumeric()) |
4.无法判断浮点数
| |
| num5 = '4.3' |
| print(num5.isdigit()) |
| print(num5.isdecimal()) |
| print(num5.isnumeric()) |
字符串类型(str)

定义
| |
| name1 = 'xiao' |
| name2 = "lili" |
| name3 = """ricky""" |
类型转换
| |
| >>> type(str([1,2,3])) |
| <class 'str'> |
| >>> type(str({"name":"xiao","age":18})) |
| <class 'str'> |
| >>> type(str((1,2,3))) |
| <class 'str'> |
| >>> type(str({1,2,3,4})) |
| <class 'str'> |
内置方法(优先掌握)
| str1 = 'hello python!' |
| |
| |
| |
| print(str1[6]) |
| p |
| |
| print(str1[-4]) |
| h |
| |
| print(str1[0]='H') |
| |
| |
| |
| |
| >>> str1[0:9] |
| hello pyt |
| |
| >>> str1[0:9:2] |
| hlopt |
| |
| >>> str1[::-1] |
| !nohtyp olleh |
| |
| |
| |
| print(len(str1)) |
| 13 |
| |
| |
| |
| >>> 'hello' in str1 |
| True |
| |
| >>> 'tony' not in str1 |
| True |
| |
| |
| |
| str1 = ' life is short! ' |
| print(str1.strip()) |
| life is short! |
| |
| |
| str2 = '**tony**' |
| print(str2.strip('*')) |
| tony |
| |
| |
| |
| str3='hello world' |
| print(str3.split()) |
| ['hello', 'world'] |
| |
| str4 = '127.0.0.1' |
| print (str4.split('.')) |
| ['127', '0', '0', '1'] |
| |
| |
| |
| str5 = '今天是晴天!' |
| for line in str5: |
| print(line) |
| |
| 今 |
| 天 |
| 是 |
| 晴 |
| 天 |
| ! |
内置方法(需要掌握)
| 1.strip, lstrip, rstrip (去除空格(strip)或者指定字符) |
| text = '**Hello, World!**' |
| |
| stripped_text = text.strip() |
| print(stripped_text) |
| |
| left_stripped_text = text.lstrip() |
| print(left_stripped_text) |
| |
| right_stripped_text = text.rstrip() |
| print(right_stripped_text) |
| |
| 2.lower(),upper() (大小写转换) |
| text = 'hello' |
| uppercase_text = text.upper() |
| print(uppercase_text) |
| |
| text = 'WORLD' |
| lowercase_text = text.lower() |
| print(lowercase_text) |
| |
| 3.startswith,endswith (首尾字符判断) |
| text = 'Python is fun' |
| |
| result = text.startswith('Python') |
| print(result) |
| |
| |
| |
| result = text.endswith('fun') |
| print(result) |
| |
| |
| 4.格式化输出之format |
| 之前我们使用%s来做字符串的格式化输出操作,在传值时,必须严格按照位置与%s一一对应,而字符串的内置方法format则提供了一种不依赖位置的传值方式 |
| |
| 案例: |
| |
| |
| str4 = 'my name is {name}, my age is {age}!'.format(age=18,name='tony') |
| print(str4) |
| 'my name is tony, my age is 18!' |
| |
| str4 = 'my name is {name}{name}{name}, my age is {name}!'.format(name='tony', age=18) |
| print(str4) |
| 'my name is tonytonytony, my age is tony!' |
| format的其他使用方式(了解) |
| |
| |
| str4 = 'my name is {}, my age is {}!'.format('tony', 18) |
| print(str4) |
| my name is tony, my age is 18! |
| |
| str4 = 'my name is {0}, my age is {1}!'.format('tony', 18) |
| print(str4) |
| my name is tony, my age is 18! |
| |
| str4 = 'my name is {1}, my age is {0}!'.format('tony', 18) |
| print(str4) |
| my name is 18, my age is tony! |
| |
| str4 = 'my name is {1}, my age is {1}!'.format('tony', 18) |
| print(str4) |
| my name is 18, my age is 18! |
| |
| 5.split,rsplit |
| |
| str5='C:/a/b/c/d.txt' |
| print(str5.split('/',1)) |
| ['C:', 'a/b/c/d.txt'] |
| |
| |
| str5='a|b|c' |
| print(str5.rsplit('|',1)) |
| ['a|b', 'c'] |
| |
| 6.join |
| |
| print('%'.join('hello')) |
| 'h%e%l%l%o' |
| print('|'.join(['tony','18','read'])) |
| 'tony|18|read' |
| |
| 7.replace |
| |
| str7 = 'my name is tony, my age is 18!' |
| str7 = str7.replace('18', '73') |
| print(str7) |
| my name is tony, my age is 73! |
| |
| |
| >>> str7 = 'my name is tony, my age is 18!' |
| >>> str7 = str7.replace('my', 'MY',1) |
| >>> str7 |
| 'MY name is tony, my age is 18!' |
| |
| 8.isdigit |
| |
| str8 = '5201314' |
| print(str8.isdigit()) |
| True |
| |
| str8 = '123g123' |
| print(str8.isdigit()) |
| False |
内置方法(了解操作)
| |
| |
| msg='tony say hello' |
| print(msg.find('o',1,3)) |
| 1 |
| |
| print(msg.index('e',2,4)) |
| |
| |
| msg = "hello everyone" |
| print(msg.count('e')) |
| 4 |
| print(msg.count('e',1,6)) |
| 1 |
| |
| |
| name='tony' |
| print(name.center(30,'-')) |
| -------------tony------------- |
| print(name.ljust(30,'*')) |
| tony************************** |
| print(name.rjust(30,'*')) |
| **************************tony |
| print(name.zfill(50)) |
| 0000000000000000000000000000000000000000000000tony |
| |
| |
| name = 'tony\thello' |
| print(name) |
| tony hello |
| print(name.expandtabs(1)) |
| tony hello |
| |
| |
| |
| message = 'hello everyone nice to meet you!' |
| print(message.capitalize()) |
| Hello everyone nice to meet you! |
| |
| message1 = 'Hi girl, I want make friends with you!' |
| print(message1.swapcase()) |
| hI GIRL, i WANT MAKE FRIENDS WITH YOU! |
| |
| msg = 'dear my friend i miss you very much' |
| print(msg.title() |
| Dear My Friend I Miss You Very Much |
| |
| |
| |
| num1 = b'4' |
| num2 = u'4' |
| num3 = '四' |
| num4 = 'Ⅳ' |
| |
| |
| >>> num1.isdigit() |
| True |
| >>> num2.isdigit() |
| True |
| >>> num3.isdigit() |
| False |
| >>> num4.isdigit() |
| False |
| |
| |
| >>> num2.isdecimal() |
| True |
| >>> num3.isdecimal() |
| False |
| >>> num4.isdecimal() |
| False |
| |
| |
| >>> num2.isnumeric() |
| True |
| >>> num3.isnumeric() |
| True |
| >>> num4.isnumeric() |
| True |
| |
| |
| >>> num5 = '4.3' |
| >>> num5.isdigit() |
| False |
| >>> num5.isdecimal() |
| False |
| >>> num5.isnumeric() |
| False |
| |
| ''' |
| 总结: |
| 最常用的是isdigit,可以判断bytes和unicode类型,这也是最常见的数字应用场景 |
| 如果要判断中文数字或罗马数字,则需要用到isnumeric。 |
| # 这三种方法无法判断浮点数 |
| ''' |
| |
| |
| >>> name = 'tony123' |
| >>> name.isalnum() |
| True |
| >>> name.isalpha() |
| False |
| >>> name.isidentifier() |
| True |
| >>> name.islower() |
| True |
| >>> name.isupper() |
| False |
| >>> name.isspace() |
| False |
| >>> name.istitle() |
| False |
列表类型 (list)

定义
类型转换
| |
| >>> list('wdad') |
| >>> list([1,2,3]) |
| >>> list({"name":"xiao","age":18}) |
| >>> list((1,2,3)) |
| >>> list({1,2,3,4}) |
内置方法(优先掌握)
| |
| |
| my_friends=['tony','xiao','tom',4,5] |
| print(my_friends[0]) |
| |
| print(my_friends[-1]) |
| |
| |
| my_friends = ['tony','jack','xiao',4,5] |
| print(my_friends[1]) = 'martthow' |
| print(my_friends) |
| ['tony', 'martthow', 'xiao', 4, 5] |
| |
| |
| |
| |
| print(my_friends[0:4]) |
| ['tony', 'xiao', 'tom', 4] |
| |
| print(my_friends[0:4:2]) |
| ['tony', 'tom'] |
| |
| |
| print(len(my_friends)) |
| 5 |
| |
| |
| print('tony' in my_friends) |
| True |
| print('tonc' not in my_friends) |
| True |
| |
| |
| |
| |
| l1 = ['a','b','c'] |
| l1.append('d') |
| print(l1) |
| ['a', 'b', 'c', 'd'] |
| |
| |
| l1.extend(['a','b','c']) |
| print(l1) |
| ['a', 'b', 'c', 'd', 'a', 'b', 'c'] |
| |
| |
| l1.insert(0,"first") |
| print(l1) |
| ['first', 'a', 'b', 'c', 'alisa', 'a', 'b', 'c'] |
| |
| |
| |
| l = [11,22,33,44] |
| del l[2] |
| print(l) |
| [11,22,44] |
| |
| |
| l = [11,22,33,22,44] |
| res=l.pop() |
| print(res) |
| 44 |
| res=l.pop(1) |
| print(res) |
| 22 |
| |
| |
| l = [11,22,33,22,44] |
| res=l.remove(22) |
| print(res) |
| None |
| |
| |
| l = [11,22,33,44] |
| l.reverse() |
| print(l) |
| [44,33,22,11] |
| |
| |
| |
| l = [11,22,3,42,7,55] |
| l.sort() |
| print(l) |
| [3, 7, 11, 22, 42, 55] |
| l = [11,22,3,42,7,55] |
| l.sort(reverse=True) |
| print(l) |
| [55, 42, 22, 11, 7, 3] |
| |
| |
| l1=[1,2,3] |
| l2=[2,] |
| print(l2 > l1) |
| True |
| |
| s1='abc' |
| s2='az' |
| print(s2 > s1) |
| True |
| |
| l = ['A','z','adjk','hello','hea'] |
| l.sort() |
| print(l) |
| ['A', 'adjk', 'hea', 'hello','z'] |
| |
| |
| - 需要注意的是,sort() 方法会直接修改原列表,而不会返回一个新的排序后的列表。 |
| - 如果你需要保留原列表,可以使用 sorted() 函数 |
| |
| |
| numbers = [5, 2, 9, 1, 7] |
| sorted_numbers = sorted(numbers) |
| print(sorted_numbers) |
| print(numbers) |
| |
| - sort() 方法默认是按照元素的大小进行排序,如果需要自定义排序规则,可以使用 key 参数,传入一个函数 |
| - 例如,按照元素的绝对值进行排序: |
| |
| |
| numbers = [-5, 2, -9, 1, 7] |
| numbers.sort(key=abs) |
| print(numbers) |
| - key 参数指定的函数将应用于列表中的每个元素,用于提取排序的关键字。 |
| |
| |
| |
| for line in my_friends: |
| print(line) |
| 'tony' |
| 'jack' |
| 'xiao' |
| 4 |
| 5 |
内置方法(了解操作)
| l=[1,2,3,4,5,6] |
| print(l[0:3:1]) |
| [1, 2, 3] |
| print([2::-1]) |
| [3, 2, 1] |
| |
| |
| print(l[::-1]) |
| [6, 5, 4, 3, 2, 1] |
元组类型 (tuple)
元组与列表类似,也是可以存多个任意类型的元素,不同之处在于元组的元素不能修改,即元组相当于不可变的列表,用于记录多个固定不允许修改的值,单纯用于取

定义
| |
| countries = ("中国","美国","英国") |
| |
| countries = ("中国",) |
类型转换
| |
| print(tuple('wdad')) |
| print(tuple([1,2,3])) |
| print(tuple({"name":"xiao","age":18})) |
| print(tuple((1,2,3))) |
| print(tuple({1,2,3,4})) |
| |
内置方法
| tuple1 = (1, 'hhaha', 15000.00, 11, 22, 33) |
| |
| print(tuple1[0]) |
| 1 |
| print(tuple1[-2]) |
| 22 |
| tuple1[0] = 'hehe' |
| |
| |
| print(tuple1[0:6:2]) |
| (1, 15000.0, 22) |
| |
| |
| print(len(tuple1)) |
| 6 |
| |
| |
| print('hhaha' in tuple1) |
| True |
| print('hhaha' not in tuple1) |
| False |
| |
| |
| for line in tuple1: |
| ... print(line) |
| 1 |
| hhaha |
| 15000.0 |
| 11 |
| 22 |
| 33 |
字典类型 (dict)

定义
| |
| info={'name':'tony','age':18,'sex':'male'} |
| |
| info=dict(name='tony',age=18,sex='male') |
类型转换
| |
| info = dict([['name','tony'],('age',18)]) |
| print(info) |
| {'age': 18, 'name': 'tony'} |
| |
| |
| {}.fromkeys(('name','age','sex'),None) |
| {'age': None, 'sex': None, 'name': None} |
内置方法(优先掌握)
| |
| |
| dic = { |
| ... 'name': 'xxx', |
| ... 'age': 18, |
| ... 'hobbies': ['play game', 'basketball'] |
| ... } |
| print(dic['name']) |
| 'xxx' |
| print(dic['hobbies'][1]) |
| 'basketball' |
| |
| dic['gender'] = 'male' |
| print(dic) |
| {'name': 'tony', 'age': 18, 'hobbies': ['play game', 'basketball'],'gender':'male'} |
| |
| dic['name'] = 'tony' |
| print(dic) |
| {'name': 'tony', 'age': 18, 'hobbies': ['play game', 'basketball']} |
| |
| |
| |
| print(len(dic)) |
| 3 |
| |
| |
| |
| print('name' in dic) |
| True |
| |
| |
| |
| dic.pop('name') |
| print(dic) |
| {'age': 18, 'hobbies': ['play game', 'basketball']} |
| |
| |
| |
| dic = {'age': 18, 'hobbies': ['play game', 'basketball'], 'name': 'xxx'} |
| |
| print(dic.keys()) |
| dict_keys(['name', 'age', 'hobbies']) |
| |
| print(dic.values()) |
| dict_values(['xxx', 18, ['play game', 'basketball']]) |
| |
| print(dic.items()) |
| dict_items([('name', 'xxx'), ('age', 18), ('hobbies', ['play game', 'basketball'])]) |
| |
| |
| |
| |
| >>> for key in dic: |
| ... print(key) |
| ... |
| age |
| hobbies |
| name |
| |
| >>> for key in dic.keys(): |
| ... print(key) |
| ... |
| age |
| hobbies |
| name |
| |
| >>> for key in dic.values(): |
| ... print(key) |
| ... |
| 18 |
| ['play game', 'basketball'] |
| xxx |
| |
| >>> for key in dic.items(): |
| ... print(key) |
| ... |
| ('age', 18) |
| ('hobbies', ['play game', 'basketball']) |
| ('name', 'xxx') |
| |
| |
| - 字典的排序是通过字典的键来进行的,使用 sorted() 函数可以对字典进行排序。 |
| |
| my_dict = {'apple': 5, 'banana': 2, 'orange': 8, 'grape': 1} |
| |
| |
| sorted_dict = sorted(my_dict.items()) |
| print(sorted_dict) |
| |
| |
| - 在示例中,sorted() 函数对字典 my_dict 的键进行了排序,返回了一个按键排序的元组列表。 |
| - 如果需要按值进行排序,可以使用 key 参数指定排序的关键字: |
| |
| my_dict = {'apple': 5, 'banana': 2, 'orange': 8, 'grape': 1} |
| |
| |
| sorted_dict = sorted(my_dict.items(), key=lambda x: x[1]) |
| print(sorted_dict) |
| |
| |
| - 在这个示例中,key` 参数指定了按值排序,并使用了 lambda 函数提取元组中的第二个元素(值)作为排序的关键字。 |
内置方法(需要掌握)
| 1.get() |
| |
| dic= {'k1':'xiao','k2':'Tony','k3':'JY'} |
| print(dic.get('k1')) |
| 'xiao' |
| res=dic.get('xxx') |
| print(res) |
| None |
| res=dic.get('xxx',666) |
| print(res) |
| 666 |
| |
| |
| 2.pop() |
| |
| dic= {'k1':'xiao','k2':'Tony','k3':'JY'} |
| v = dic.pop('k2') |
| print(dic) |
| {'k1': 'xiao', 'kk2': 'JY'} |
| print(v) |
| 'Tony' |
| |
| 3.popitem() |
| |
| dic= {'k1':'xiao','k2':'Tony','k3':'JY'} |
| item = dic.popitem() |
| print(dic) |
| {'k3': 'JY', 'k2': 'Tony'} |
| print(item) |
| ('k1', 'xiao') |
| |
| 4.update() |
| |
| |
| dic= {'k1':'xiao','k2':'Tony','k3':'JY'} |
| dic.update({'k1':'JN','k4':'xxx'}) |
| print(dic) |
| {'k1': 'JN', 'k3': 'JY', 'k2': 'Tony', 'k4': 'xxx'} |
| |
| 5.fromkeys() |
| |
| dic = dict.fromkeys(['k1','k2','k3'],[]) |
| print(dic) |
| {'k1': [], 'k2': [], 'k3': []} |
| |
| 6.setdefault() |
| |
| |
| dic={'k1':111,'k2':222} |
| res=dic.setdefault('k3',333) |
| print(res) |
| 333 |
| print(dic) |
| {'k1': 111, 'k3': 333, 'k2': 222} |
| |
| |
| dic={'k1':111,'k2':222} |
| res=dic.setdefault('k1',666) |
| print(res) |
| 111 |
| print(dic) |
| {'k1': 111, 'k2': 222} |
集合
集合、list、tuple、dict一样都可以存放多个值,但是集合主要用于:去重、关系运算

定义
| """ |
| 定义:在{}内用逗号分隔开多个元素,集合具备以下三个特点: |
| 1:每个元素必须是不可变类型 |
| 2:集合内没有重复的元素 |
| 3:集合内元素无序 |
| """ |
| s = {1,2,3,4} |
| |
| |
| |
| |
| d = {} |
| s = set() |
类型转换
| |
| >>> s = set([1,2,3,4]) |
| >>> s1 = set((1,2,3,4)) |
| >>> s2 = set({'name':'xiao',}) |
| >>> s3 = set('xu') |
| >>> print(s,s1,s2,s3) |
| {1, 2, 3, 4} {1, 2, 3, 4} {'name'} {'x', 'u'} |
内置方法
1. 关系运算 (集合的交并差)
我们定义两个集合friends与friends2来分别存放两个人的好友名字,然后以这两个集合为例讲解集合的关系运算
| friends1 = {"zero","kevin","xiao","xu"} |
| friends2 = {"Jy","ricky","xiao","xu"} |
两个集合的关系如下图所示

| |
| >>> friends1 | friends2 |
| {'kevin', 'ricky', 'zero', 'xiao', 'Jy', 'xu'} |
| |
| |
| >>> friends1 & friends2 |
| {'xiao', 'xu'} |
| |
| |
| >>> friends1 - friends2 |
| {'kevin', 'zero'} |
| >>> friends2 - friends1 |
| {'ricky', 'Jy'} |
| |
| |
| >>> friends1 ^ friends2 |
| {'kevin', 'zero', 'ricky', 'Jy'} |
| |
| |
| >>> friends1 == friends2 |
| False |
| |
| |
| |
| >>> {1,2,3} > {1,2} |
| True |
| >>> {1,2,3} >= {1,2} |
| True |
| |
| >>> {1,2,3} > {1,3,4,5} |
| False |
| >>> {1,2,3} >= {1,3,4,5} |
| False |
| |
| |
| >>> {1,2} < {1,2,3} |
| True |
| >>> {1,2} <= {1,2,3} |
| True |
2. 去重
集合去重复有局限性
示例如下
| l=['a','b',1,'a','a'] |
| s=set(l) |
| print(s) |
| {'b', 'a', 1} |
| l_new=list(s) |
| print(l_new) |
| ['b', 'a', 1] |
| |
| |
| l=[ |
| {'name':'lili','age':18,'sex':'male'}, |
| {'name':'jack','age':73,'sex':'male'}, |
| {'name':'tom','age':20,'sex':'female'}, |
| {'name':'lili','age':18,'sex':'male'}, |
| {'name':'lili','age':18,'sex':'male'}, |
| ] |
| |
| new_l=[] |
| |
| for dic in l: |
| if dic not in new_l: |
| new_l.append(dic) |
| print(new_l) |
| |
| [ |
| {'age': 18, 'sex': 'male', 'name': 'lili'}, |
| {'age': 73, 'sex': 'male', 'name': 'jack'}, |
| {'age': 20, 'sex': 'female', 'name': 'tom'} |
| ] |
3. 其他操作
| |
| s={'a','b','c'} |
| print(len(s)) |
| 3 |
| |
| |
| 'c' in s |
| True |
| |
| |
| for item in s: |
| ... print(item) |
| ... |
| c |
| a |
| b |
| |
| |
| |
| - add(element) 方法用于向集合中添加单个元素。 |
| |
| my_set = {1, 2, 3} |
| my_set.add(4) |
| print(my_set) |
| |
| |
| |
| - update(iterable) 方法用于向集合中添加多个元素,参数是一个可迭代对象。 |
| |
| my_set = {1, 2, 3} |
| my_set.update([3, 4, 5]) |
| print(my_set) |
| |
| |
| |
| |
| |
| - remove(element) 方法用于移除集合中的指定元素,如果元素不存在则会引发 KeyError。 |
| |
| my_set = {1, 2, 3, 4, 5} |
| my_set.remove(3) |
| print(my_set) |
| |
| |
| |
| |
| - discard(element) 方法用于移除集合中的指定元素,如果元素不存在则不会引发错误。 |
| |
| my_set = {1, 2, 3, 4, 5} |
| my_set.discard(3) |
| print(my_set) |
| |
| |
| |
| |
| - pop() 方法用于随机移除集合中的一个元素,如果集合为空则引发 KeyError。(集合输出的第一个元素删掉) |
| |
| my_set = {1, 2, 3, 4, 5} |
| removed_element = my_set.pop() |
| print(removed_element) |
| print(my_set) |
| |
数据类型总结
按存值个数区分 |
|
只能存一个值:可称为标量/原子类型 |
数字类型、字符串、布尔 |
可以存放多个值:可称为容器类型 |
列表、元祖、字典、集合 |
按照访问方式区分 |
|
直接访问:只能通过变量名访问整个值 |
数字类型 |
顺序访问:可以通过索引访问指定的值,索引代表顺序,又称为序列类型 |
字符串、列表、元祖 |
key访问:可以用key访问指定的值,又称为映射类型 |
字典 |
按可变不可变区分 |
|
可变类型 |
列表、字典 |
不可变类型 |
数字、字符串、元祖、布尔、集合 |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏