当前位置: 移动技术网 > IT编程>脚本编程>Python > 荐 python的列表,元组,字典,集合的初步学习

荐 python的列表,元组,字典,集合的初步学习

2020年07月14日  | 移动技术网IT编程  | 我要评论

一、列表

列表是可变的,可以使用两种方式创建列表

# 1.
list1 = [1, 2, 3, 4, 5]
print(list1)
# 2.
str = "12345"
list2 = list(str)
print(list2)

list里面的元素的类型不一定要相同

list3 = [1, "helloWorld", ("china", "beijing"), {"china": "beigin", "American": "NewYork"}, [4, 5, 6]]
print(list3)

可以往list里面添加元素

list3.append("China")

可以在list中删除元素

list3.remove(1)

可以翻转List

list3.reverse()

需要注意的是,如果两个列表赋一样的值,但是他们的内存地址是不一样的

# 比较内存地址
list4 = [1, 2, 3, 4, 5]
list5 = [1, 2, 3, 4, 5]
print(id(list4))
print(id(list5))
print(list4 is list5)

输出>>>
136628944
8177024
False

二、 字符串

str是不可变的,即str里面的元素不允许被修改和删除
newStr = “helloWorld”

# 这样是不被允许的
newStr[2]= "Y"

对str进行切片

# newStr(begin,end,step) 第一个参数代表起始位置,第二个参数代表终点位置,第三个元素代表步长
# 表示从0到2,其中0包含,2不包含,即左闭右开
sp = newStr[:2]
print(sp)

console>>>
 he

# 对newStr字符串进行切片,其中步长是2
sp = newStr[::2]
print(sp)

console>>>
hlool
# 从后往前对str字符串切片
sp = newStr[:-4:2]
print(sp)

# -1代表字符串的最后一个元素
print(sp[-1])

需要注意的是,如果两个字符串赋一样的值,但是他们的内存地址是一样的

# 比较相同字符串的内存地址
str2 = "String"
str3 = "String"
print(id(str2))
print(id(str3))
print(str2 is str3)

输出>>>
39608544
39608544
True

三、元组

元组和字符串类似,是不可变的,即生成一个元组后不能在生成的元组里添加或者修改元素

创建元组的两种方式

1.
tuple1 = (1,2)
2.
# list1 = [1, 2, 3, 4, 5]
tuple2 = tuple(list1)

如果元组里面只有一个元素,那么需要在一个元素后面加上逗号

# int
tuple3 = (5)
print(type(tuple3))

输出>>>
<class 'int'>

tuple4 = (5,)
输出>>>
<class 'tuple'>

需要注意的是,如果两个元组赋一样的值,但是他们的内存地址是不一样的

tuple4 = (5,)
tuple5 = (5,)
print(id(tuple4))
print(id(tuple5))
print(tuple4 is tuple5)

conlose>>>
2535664
6161168
False

四、集合

集合输出是无序的,在集合中,相同的元素不可以重复出现,只能保留一个,集合中的元素的类型也可以不一致但是不能是list和dict,因为集合不可修改,但是集合中的列表和字典可以修改,这会产生矛盾

创建集合的两种方式

# 集合
set1 = set('helloworld')
set2 = {'h', 'w', 4, 5}

console set1>>>
{'o', 'l', 'r', 'h', 'e', 'd', 'w'}

从set1的输出结果我们可以看到1.输出结果是无序的 2.重复的元素只保留一条

字典

字典是键值对,我们先来创建一个字典

# 字典
dict1 = {"hello": "world", "china": "beijing", "list": [1, 2, 3], "tuple": (1, 2, 3), 4: 5}

1.字典中,相同的key只能对应一个value,如果有多个value,那么取最后一个value

dict1 = {"hello": "world", "china": "beijing", "hello": "china"}
print(dict1)

console>>>
{'hello': 'china', 'china': 'beijing'}

2.修改字典

# 修改字典
dict1["tuple"] = "china"
result1 = dict1.get("tuple")
print(result1)

字典中键必须不可变,所以不能用列表和字典来充当Key

本文地址:https://blog.csdn.net/weixin_38828673/article/details/107314280

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网