>> print(type(..._python数据类型的作用是什么">
当前位置:   article > 正文

python数据类型的用途-Python 数据类型用法

python数据类型的作用是什么

1:整数类型(int)

1:用途

int:记录年龄,等级,岁月等

2:定义方式

>>> x = 10

>>> id(x)

1489303616

>>> type(x)

2:浮点数类型(float)

1:用途

float:记录重量,工资等

2:定义方式

>>> x = 1.5

>>> y = 8.8

>>> type(x)

3:数据类型之间转换

>>> age = "134423"

>>> print(type(age))

>>> age = int(age)

>>> type(age)

警告

纯数字类型字符串可以通过int方法转换成数字类型

>>> salary = "2.5"

>>> type(salary)

>>> salary=float(salary)

>>> salary

2.5

>>> type(salary)

>>>

警告

纯浮点类型字符串可以通过float方法转换成浮点类型

4:字符串类型(str)

1:用途

主要是用来描述事物特征的

2:定义方式

x = "x"

1 2 3

1:是变量名

2:是赋值符号

3:值用"content","""content""","""content"""

3:str方法

一:根据索引取值

1:正向取值

>>>msg = "hello小白兔"

>>>msg

"hello小白兔"

索引从0开始

>>>msg[0]

"h"

>>>msg[1]

"e"

2:反向取值

索引从-1开始

"hello小白兔"

>>> msg[-1]

"兔"

>>> msg

"hello小白兔"

>>> msg[-1:-6]

""

>>> msg[-3]

"小"

>>> msg[-13]

Traceback (most recent call last):

File "", line 1, in

IndexError: string index out of range

超过范围,报错

3:步长

>>> msg

"hello小白兔"

>>> msg[0:5:2]

"hlo"

>>>

用步长方向取值

>>> msg[:]

"hello小白兔"

>>> msg[::-1]

"兔白小olleh"

二:切片取值(左闭右开)

1:正常从左向右

>>> msg

"hello小白兔"

>>> msg[2:]

"llo小白兔"

>>> msg[:]

"hello小白兔"

>>> msg[1:]

"ello小白兔"

>>> msg[1:4]

"ell"

2:反向取值

​> msg

>>> msg[4:0:-1

... ]

"olle"

>>> msg[7:5:-1]

"兔白"

>>> msg[7:4:-1]

"兔白小"

三:长度

​msg="hello小白兔"

>>> msg

"hello小白兔"

>>> len(msg)

8

四:成员运算(in,not in)

>>> msg

"hello小白兔"

>>> "h" in msg

True

>>> "aaa" in msg

False

>>> "ee" in msg

False

>>> "alex" in msg

False

>>> "a" not in msg

True

>>>

5:非常重重要(split,strip)

split方法

>>> msg

"hello小白兔"

>>> msg.split("小")

["hello", "白兔"]

>>> msg.split("o")

["hell", "小白兔"]

>>> msg.split("l")

["he", "", "o小白兔"]

>>>

strip方法

>>> msg = " hello小白兔"

>>> msg1 = "hello小白兔 "

>>> msg3 = " hello小白兔 "

>>> msg4 = " hello 小白兔 "

>>> msg

" hello小白兔"

>>> msg1

"hello小白兔 "

>>> msg3

" hello小白兔 "

>>> msg4

" hello 小白兔 "

>>>

>>>

>>> msg1

"hello小白兔 "

>>> msg1.strip()

"hello小白兔"

>>> msg1

"hello小白兔 "

>>> msg3

" hello小白兔 "

>>> msg3.strip()

"hello小白兔"

>>> msg4

" hello 小白兔 "

>>> msg4.strip()

"hello 小白兔"

>>>

7:重要方法

1、strip,lstrip,rstrip

>>> msg = " hellowstrip "

>>> msg.strip()

"hellowstrip"

>>> msg.lstrip()

"hellowstrip "

>>> msg.rstrip()

" hellowstrip"

>>>

2、lower,upper

>>> msg = "Alex"

>>> msg.lower()

"alex"

>>> msg.upper()

"ALEX"

>>>

3、startswith,endswith

>>> msg

"Alex"

>>> msg.startswith("al")

False

>>> msg.startswith("A")

True

>>> msg

"Alex"

>>> msg.endswith("x")

True

>>> msg

"Alex"

>>> msg.endswith("x")

True

>>> msg.endswith("x", 1, 2)

False

>>> msg.endswith("e", 1, 2)

False

>>> msg.endswith("l", 1, 2)

True

>>> msg.endswith("l", 1, 2)

True

>>>

4、format

>>> "hello word: {}".format("strip")

"hello word: strip"

>>>

>>> "my name is {},age {}".format("Seven", 18)

"my name is Seven,age 18"

>>>

5、split,rsplit

>>> name = "fdsfa "

>>> name

"fdsfa "

>>> name.split("s")

["fd", "fa "]

>>>

>>> name.rsplit("f")

["", "ds", "a "]

6、join

>>> name = "sfsaf"

>>> name

"sfsaf"

>>> "-".join(name)

"s-f-s-a-f"

>>> "*".join(name)

"s*f*s*a*f"

>>>

7、replace

>>> "zero".replace("o","8")

"zer8"

>>>

8、isdigit

>>> "100".isdigit()

True

>>> "afds".isdigit()

False

>>> "110032fdf".isdigit()

False

>>>

8:了解方法

1、find,rfind,index,rindex,count

>>> name = "hello word"

>>> name.find("o",1,3) # 顾头不顾尾,找不到则返回-1不会报错,找到了则显示索引

-1

>>> name.index("o",1,3) # 顾头不顾尾,找不到则报错,找到了则显示索引

Traceback (most recent call last):

File "", line 1, in

ValueError: substring not found

>>> name.count("e",3,7) # 顾头不顾尾,如果不指定范围则查找所有

0

>>> name.count("o",3,7)

1

>>>

2、center,ljust,rjust,zfill

>>> "alex".center(50,"*")

"***********************alex***********************"

>>> "alex".ljust(50,"*")

"alex**********************************************"

>>> "alex".rjust(50, "*")

"**********************************************alex"

>>> "alex".zfill(50)

"0000000000000000000000000000000000000000000000alex"

>>>

3、expandtabs

>>> "name nihao".expandtabs(2)

"name nihao"

>>> "name nihao".expandtabs()

"name nihao"

>>> "name nihao".expandtabs(3)

"name nihao"

>>> "name nihao".expandtabs(3)

4、captalize,swapcase,title

>>> name ="absfds"

>>> name.capitalize()

"Absfds"

>>> name.swapcase()

"ABSFDS"

>>> "asfD".swapcase()

"ASFd"

>>> "hello word".title()

"Hello Word"

5、is数字系列

#在python3中

num1=b"4" #bytes

num2=u"4" #unicode,python3中无需加u就是unicode

num3="四" #中文数字

num4="Ⅳ" #罗马数字

#isdigt:bytes,unicode

print(num1.isdigit()) #True

print(num2.isdigit()) #True

print(num3.isdigit()) #False

print(num4.isdigit()) #False

#isdecimal:uncicode

#bytes类型无isdecimal方法

print(num2.isdecimal()) #True

print(num3.isdecimal()) #False

print(num4.isdecimal()) #False

#isnumberic:unicode,中文数字,罗马数字

#bytes类型无isnumberic方法

print(num2.isnumeric()) #True

print(num3.isnumeric()) #True

print(num4.isnumeric()) #True

#三者不能判断浮点数

num5="4.3"

print(num5.isdigit())

print(num5.isdecimal())

print(num5.isnumeric())

"""

总结:

最常用的是isdigit,可以判断bytes和unicode类型,这也是最常见的数字应用场景

如果要判断中文数字或罗马数字,则需要用到isnumeric

"""

6、is其他

print("===>")

name="egon123"

print(name.isalnum()) #字符串由字母或数字组成

print(name.isalpha()) #字符串只由字母组成

print(name.isidentifier())

print(name.islower())

print(name.isupper())

print(name.isspace())

print(name.istitle())

5:列表类型

1:用途

按照位置存放多个值

2:定义方式

在[]内用逗号分隔开多个任意类型的值

l = [111, 3.1, "abc", []] #l = list(......)

print(type(l))

3:类型转换

list(传入的是可迭代数据类型)

>>> list("hello")

["h", "e", "l", "l", "o"]

>>> list(14234)

Traceback (most recent call last):

File "", line 1, in

TypeError: "int" object is not iterable

>>> list("asfsf"

... )

["a", "s", "f", "s", "f"]

>>>

4:常用操作和内置方法

1:索引次数,取值(正向,方向):即可改也可取

>>> l = [11, 22, 33, 44, 55]

>>> l

[11, 22, 33, 44, 55]

>>> l[::-1]

[55, 44, 33, 22, 11]

>>> l[2:]

[33, 44, 55]

>>> l[1:3]

[22, 33]

>>>

>>> l[5]

Traceback (most recent call last):

File "", line 1, in

IndexError: list index out of range

2:切片(顾头不顾尾巴,步长)

>> l = [1, 2, 3, 4, 5]

>>> l

[1, 2, 3, 4, 5]

>>> l[:]

[1, 2, 3, 4, 5]

>>> l[0:3]

[1, 2, 3]

>>> l[0]

1

>>> l[4]

5

>>>

3:长度

>>> l

[11, 22, 33, 44, 55]

>>> len(l)

5

4:成员运算in和not in

>>> l

[11, 22, 33, 44, 55]

>>> len(l)

5

>>> 11 in l

True

>>> 11 not in l

False

>>> 77 in l

False

5:追加

>

>>> l= [11, 22, 33, 44, 55]

>>> l

[11, 22, 33, 44, 55]

>>> l.append("66")

>>> l.append("abc")

>>> l

[11, 22, 33, 44, 55, "66", "abc"]

1:往指定位置插入值

>>> l

[11, 22, 33, 44, 55, "66", "abc"]

>>> l.insert(0,"aa")

>>> l

["aa", 11, 22, 33, 44, 55, "66", "abc"]

>>> l.insert(3,"bb")

>>> l

["aa", 11, 22, "bb", 33, 44, 55, "66", "abc"]

>>>

6:删除

del 删除是通用的,不是列表专属

>>> ll = [111, 222, 333, 444]

>>> ll

[111, 222, 333, 444]

>>> del ll[0]

>>> ll

[222, 333, 444]

>>>

1:pop方法

pop没有参数默认从索引-1开始删除,

>>> ll = [1, 2, 3, 4, 5, 6]

>>> ll

[1, 2, 3, 4, 5, 6]

>>> ll.pop()

6

>>> ll

[1, 2, 3, 4, 5]

>>> ll.pop()

5

>>> ll

[1, 2, 3, 4]

>>> ll.pop(0)

1

>>> ll

[2, 3, 4]

>>>

2:remove用法

>>> ll = [1, 2, 3, 4, 5, 6]

>>> ll

[1, 2, 3, 4, 5, 6]

>>> ll.remove(1)

>>> ll

[2, 3, 4, 5, 6]

>>> ll.remove(5)

>>>

7:循环

>>> ll = [1, 2, 3, 4, 5, 6]

>>> ll

[1, 2, 3, 4, 5, 6]

>>> for i in ll:

... print(i)

...

1

2

3

4

5

6

>>>

8:重要方法

# 需要掌握的操作

#count

>>> ll = [11, 22, 33, 44, 55]

>>> ll.count(11)

1

>>> ll.append(11)

>>> ll.count(11)

2

>>> ll

[11, 22, 33, 44, 55, 11]

## sort

>>>

>>> ll = [10, -1, 3, 2, 11, 7]

>>> ll.sort()

>>> ll

[-1, 2, 3, 7, 10, 11]

>>> ll.sort(reverse=True)

>>> ll

[11, 10, 7, 3, 2, -1]

>>>

##clear

>>> ll

[11, 10, 7, 3, 2, -1]

>>> ll

[11, 10, 7, 3, 2, -1]

>>> ll.clear()

>>>

#reverse

>>> ll = ["a","c",1,4]

>>> ll

["a", "c", 1, 4]

>>> ll.reverse()

>>> ll

[4, 1, "c", "a"]

>>>

# extend

>>>

>>> ll = [11, 22, 33]

>>> ll.extend(["a", "b", "c"])

>>> ll

[11, 22, 33, "a", "b", "c"]

>>> ll.append(["hehe", "good"])

>>> ll

[11, 22, 33, "a", "b", "c", ["hehe", "good"]]

## copy

l1=[11,22,33]

# l1列表内存存储

# 索引0 值11的内存地址

# 索引1 值22内存地址

# 索引2 值33内存地址

# l2=l1.copy() # 等同于l4=l1[:]

# l2列表内存存储

# 索引0 值11的内存地址

# 索引1 值22内存地址

# 索引2 值33内存地址

# l2[0]=4444

# print(l2) # [4444, 22, 33]

# print(l1) # [11, 22, 33]

>>> l1 = [11, 22, 33]

>>> l1

[11, 22, 33]

>>> id(l1)

53887432

>>> l2 = l1.copy() or l2 = l1[:]

>>> id(l2)

53887944

>>> l3 = l1

>>> id(l3)

53887432

# l3=l1

# l3[0]=4444

# print(l3)

# print(l1)

5:总结

list是能存储多个值,有序,可变

6:元组数据类型

1、用途:元组就是一个不可变的列表

2、定义方式: 在小括号()内用逗号分隔开多个任意类型的值

l = [1, 2, 3]

t = (1, 2, 3) # t = tuple((111,222,333)) or t = tuple(1,)

print(type(t))

类型转换

tuple(可迭代数据类型) # ===> 元组

list(可迭代数据类型) # ===> 列表

l1 = ["a", "b", "c", "d"]

s1 = "abcedfghijk"

print(tuple(l1))

print(tuple(s1))

3、常用操作+内置的方法

优先掌握的操作:

1、按索引取值(正向取+反向取):只能取

l2 = (1, 2, 3, 4, 5, 6, 7, 8, 9)

print(l2)

print(l2[0])

print(l2[-1:1:-1])

2、切片(顾头不顾尾,步长)

t = (1, 2, 3)

print(t[0:2])

print(t)

3、长度

t = (1, 222, 333)

print(len(t))

4、成员运算in和not in

t = (1, 2, 3, 4)

print(4 in t)

5、循环

t = [0, 1, 2, 3, 4]

for i in t:

print(i)

需要掌握的内置方法

index根据参数找索引

count统计参数出现的次数

t = (4, 3, 2, 4, 2, 1, 5, 8, 11, 19, 1)

print(t.index(1))

print(t.index(8)) # 找不到则报错

print(t.count(1))

7:字典数据类型

1、用途

存多个不同属性的值,用key对应value,key必修是不可变类型,key通常应该是

​字符串类型,因为字符串类型对值value会有解释说明的效果

2、定义方式:

在{}内用逗号分隔开多个key:value元素,其中key必须是不可变类型,并且key不同重复

而value可以是任意类型

dic = {"k1": 1, "k2": 2, "k3": 3} # dic = dict({"k1": 1, "k2": 2, "k3":3})

print(type(dic))

d = {"k1": 1, "k2": 2, "k3": 3}

print(d)

3:类型转换

d = [("name", "egon"), ["age", 18], ("gender", "male")]

print(d)

print(dict(d))

res=dict(x=1,y=2,z=3)

print(res)

4:定义空

定义空

d={} # 定义空字典

print(type(d))

d = dict()

s=""

print(type(s))

l=[]

print(type(l))

t=()

print(type(t))

t=("abc",) # 当元组内只有一个元素时,必须加逗号

print(t)

print(type(t))

# s=set() # 定义空集合

5:常用操作+内置的方法

优先掌握的操作:

1、按key存取值:可存可取

d={"name":"egon","age":18, "salary":4}

l=[1,2,3]

print(d["name"])

print(l[0])

d["gender"]="male" # 可以通过不存在的key完成赋值操作来达到为字典添加值的效果

print(d)

l[3]=4 # 列表不行

2、长度len

d={"name":"egon","age":18, "gender": "male"}

print(len(d))

3、成员运算in和not in:判断的是字典的key

d={"name":"egon","age":18}

print("name" in d) # 判断的字典的key

print("egon" in d) # 判断的不是value,结果为False

4、删除

a:通用删除法

d={"name":"egon","age":18, "gender": "male"}

del d["gender"]

print(d)

b:删除-》取走

res=d.popitem() # 随机删除,返回一个删除元素的小元组

print(res)

res=d.pop("name") # 返回key对应的那一个值

print(res)

print(d)

#5、键keys(),值values(),键值对items()

"""

Python 2.7.18 (v2.7.18:8d21aa21f2, Apr 19 2020, 20:48:48)

[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darwin

Type "help", "copyright", "credits" or "license" for more information.

# >>> d={"name":"egon","age":18}

# >>>

# >>> d.keys()

# ["age", "name"]

# >>> d.values()

# [18, "egon"]

# >>> d.items()

[("age", 18), ("name", "egon")]

"""

#6、循环

d={"name":"egon","age":18, "gender": "male"}

for k in d.keys():

print(k)

for k in d:

print(k)

for v in d.values():

print(v)

for k,v in d.items(): # k,v=("age", 18)

print(k,v)

字典需要掌握的内置方法

clear

d={"name":"egon","age":18, "gender": "male"}

d.clear()

print(d)

update

d.update(age=19,gender="male")

d.update({"age":19,"gender":"male"})

print(d)

get

print(d.get("nama")) # key不存在不会报错,会返回None

print(d["nama"]) # key不存在则报错

了解**

快速初始化好一个字典

d={}.fromkeys(["name","age","gender"],None)

print(d)

d={"age":18}

保证字典中肯定有一个key是"name"

if "name" not in d:

d["name"]="egon"

d["name"]

val=d.setdefault("name","egon")

print(d)

print(val)

8:set数据类型

1:引子

friends1=["zero","kevin","jason","egon"]

friends2=["jy","ricky","jason","egon"]

l=[]

for name in friends1:

if name not in friends2:

l.append(name)

print(l)

2:用途:

去重,关系运算

3:定义方式

在{}内用逗号分隔开多个元素,元素的特点如下:

1:无序

s1={"aaa",111,"ddd"}

print(s1)

print(s1)

print(s1)

2:元素必须是不可变类型

s1={1,2.2,"abc",(1,2),[]}

3: 集合内元素不能重复

s1={1,1,1,1,1,1,1,1,1,1,1,} # s1=set(...)

print(s1)

print(type(s1))

s2=set()

print(type(s2))

4:类型转换

set(可迭代数据类型)

res=set("hello")

print(res)

print("".join(res))

res=set([111,222,333,444,111,111])

print(res)

print(list(res))

去重

res=set([111,[222],[222],333,444,111,111])

src_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 src_l:

if dic not in new_l:

new_l.append(dic)

print(new_l)

print(id(src_l[0]))

print(id(src_l[-1]))

3、常用操作+内置的方法

​1:关系运算

>>> f1 = {1, 2, 3, 4}

>>> f2 = {3, 4, 5, 6}

1,交集:两个都有的

>>> f1 & f2

{3, 4}

2,并集:两个集合的包含

>>> f1 | f2

{1, 2, 3, 4, 5, 6}

3,取第一个人独有的元素:差集

>>> f1 = {1, 2, 3, 4}

>>>f2 = {3, 4, 5, 6}

>>> f2-f1

{5, 6}

>>> f1-f2

{1, 2}

4、求两个集合独有的(即去掉共有的元素):对称差集/交叉补集

>> f1 = {1, 2, 3, 4}

>>>f2 = {3, 4, 5, 6}

>>> fs1 = f2-f1

{5, 6}

>>>fs2 = f1-f2

{1, 2}

>>>fs1|fs2

{1, 2, 5, 6}

>>> f1^f2

{1, 2, 5, 6}

5、父子集:一个集合包含另外一个集合,他们才有父子集的关系

>> f1 = {1, 2, 3, 4}

>>>f2 = {3, 4, 5, 6}

>>> f1>f2

False

>>> f2>f1

False

>>> f2==f1

False

集合1>集合2 结果True时,意味着集合1内的元素完全包含了集合2的元素

f1={1,2,3}

f2={1,2}

>>> f1={1, 2, 3}

>>> f2={1, 2}

>>> f1>f2

True

# 结果True,代表f1是f2的父集

>>>f2 < f1 # 结果True,代表s2是s1的子集

False

f1 = {1, 2, 3, 4}

f2 = {3, 2, 1, 4}

>>> f1 = {1, 2, 3, 4}

>>> f2 = {3, 2, 1, 4}

>>> f1==f2 #集合f1于f2互为父集

True

2:内置方法

1:集合for循环

>>> s = {"a", 1, 2, 4, 5, 3, "z","qq"}

>>> for i in s:

... print(i)

...

1

2

3

4

5

z

a

1,s.update()

>>> id(s)

19712456

>>> s.update({7, 8 ,11})

>>> s

{1, 2, 3, 4, 5, 7, 8, "z", 11, "a", "qq"}

>>> id(s)

19712456

>>>

2、s.clear()

>>> s

{1, 2, 3, 4, 5, 7, 8, "z", 11, "a", "qq"}

>>> s.clear()

>>> s

set()

3、s1.pop()

>>> s = {"a", 1, "z", "dd", "qq"}

>>> s.pop()

1

>>> s.pop()

"dd"

>>>

# 随机删除,把元素取走,有返回删除元素

4、s.remove() # 只是删除,没有返回元素

>>> s = {"a", "b", "c", 1, "3", 4}

{1, 4, "b", "a", "3", "c"}

>>> s.remove("aaa")

Traceback (most recent call last):

File "", line 1, in

KeyError: "aaa"

>>> s.remove(1)

>>> s

{4, "b", "a", "3", "c"}

>>> s.remove("3")

>>> s

{4, "b", "a", "c"}

5、s.discard() # 与s.remove一样都是指定元素删除

不一样的地方:当删除的元素不存在时,s.discard不会报错,

而s.remove会报错

>>> s = {"a", "b", "c", 1, "3", 4}

>>> s.discard("ssssssssss") # 指定元素不存在则报错

>>> s

{1, 4, "b", "a", "3", "c"}

>>> s.discard("a")

>>> s

{1, 4, "b", "3", "c"}

>>> s.discard("3")

>>>

s.add()

>>> s

{1, 4, "b", "c"}

>>> s.add("a")

>>> s.add("bb")

>>> s

{1, 4, "bb", "b", "a", "c"}

>>>

s.isdisjoint(s1) # 如果s1与s2没有共同的元素则返回True

>> s

{1, 4, "bb", "b", "a", "c"}

>>> s1 = {1, 4, "bb", "b", "a"}

>>> s1

{1, 4, "bb", "b", "a"}

>>> s1.isdisjoint(s)

False

>>>

总结集合set:

存多个值

无序

set集合是可变类型

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/170829
推荐阅读
相关标签
  

闽ICP备14008679号