python 中有哪些实用的方法

2.remove

A.remove(“what”) #通过元素名称,移除

3.del

del A[2] #索引移除

**

队列翻转


**

1、reverse

A.reverse() #列表翻转 例如:

[3,1,‘what’]变为[‘what’,1,3]

**

元素计数


**

1、count

C=[‘Hello’,‘Google’,‘Hello’,‘baidu’,

‘Hello’,‘baidu’,‘mofa’,‘guiyi’]

print(count(‘Hello’))

结果: 3

**

队列排序


**

1、sort

D=[2,8,44,5,12,1]

D.sort()

元组

=================================================================

定义元组

ll=(1,2,3)

print(ll)

print(ll.type())

结果 : (1,2,3)

<class ‘tuple’>

注:如果元组中只有一个元素,则这个元组后面必须要有一个",",否则元素就还是原来的类型

例如 : A=(1,) 正确 是元组

A=(1)****错误 不是元组

**

删除元素


**

由于元组不能修改,所以元组也不能删除部分元素,要删除只能删除整个元组

元素计数


1、count

C=(‘Hello’,‘Google’,‘Hello’,‘baidu’,

‘Hello’,‘baidu’,‘mofa’,‘guiyi’)

print(count(‘Hello’))

结果: 3

**

查找元素索引


**

A=(‘cal’,‘what’,1,‘2020-1-1’,‘join’)

print(“what index is:”,A.index(“what”))

结果是 : what index is:1

**

字典

=================================================================

**

字典定义:字典类型就和他的名字一样,可以向查字典一样去找,其他语言也有类似的类型。例如:Java中的HashMap , PHP中的Array等

chinese={“we”:“我们”,

“are from”:“来自”,

“China”:“中国”

}

print(chinese)

print(“China:”,chinese[“China”]) #键查找

结果: {‘we’: ‘我们’, ‘are from’: ‘来自’, ‘China’: ‘中国’}

China:中国

注意:字典的键必须是唯一的,不重复的,如果是空字典,直接用{}表示

empty={}

print(type(empty))

结果 : <class ‘dict’>

**

修改键值


**

chinese={“we”:“我们”,

“are from”:“来自”,

“China”:“中国”

}

print(chinese)

chinese[“China”]=“未来”

print(chinese)

结果:{‘we’: ‘我们’, ‘are from’: ‘来自’, ‘China’: ‘中国’}

{‘we’: ‘我们’, ‘are from’: ‘来自’, ‘China’: ‘未来’}

在这里插入图片描述

**

删除字典元素


**

chinese={“we”:“我们”,

“are from”:“来自”,

“China”:“中国”

}

print(chinese)

del chinese[“China”]

print(chinese)

在这里插入图片描述

**

清空元素


**

chinese={“we”:“我们”,

“are from”:“来自”,

“China”:“中国”

}

print(chinese)

chinese[“China”]=“未来”

del chinese[“China”]

chinese.clear()

print(chinese)

在这里插入图片描述

**

复制字典


**

用于修改复制的字典,相当于复制一个新的字典作为修改,原有的字典不变

chinese={“we”:“我们”,

“are from”:“来自”,

“China”:“中国”

}

Chi=chinese.copy()

**

创建新字典


**

SQ={“name”,“age”,“sex”}

student=dict.fromkeys(SQ)

print(student)

student1=dict.fromkeys(SQ,15)

print(student1)

在这里插入图片描述

返回键对值


chinese={“we”:“我们”,

“are from”:“来自”,

“China”:“中国”

}

print(chinese.get(“we”))

在这里插入图片描述

**

返回一个列表,包含字典所有键


**

chinese={“we”:“我们”,

“are from”:“来自”,

“China”:“中国”

}

print(chinese.keys())

在这里插入图片描述

**

返回一个列表,包含字典所有值


**

chinese={“we”:“我们”,

“are from”:“来自”,

“China”:“中国”

}

print(chinese.values())

在这里插入图片描述

**

返回一个列表,包含字典所有键和值


**

chinese={“we”:“我们”,

“are from”:“来自”,

“China”:“中国”

}

print(chinese.items())

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值