提交 66027e26 编写于 作者: 檀越@新空间's avatar 檀越@新空间 🐭

fix:切片

上级 4ec9a916
...@@ -51,7 +51,15 @@ count = len(mylist) ...@@ -51,7 +51,15 @@ count = len(mylist)
print(f"列表的元素数量总共有:{count}个") print(f"列表的元素数量总共有:{count}个")
# 7. 删除某元素在列表中的第一个匹配项
mylist = ["itcast", "itheima", "itcast", "itheima", "python"]
mylist.reverse()
print(f"通过reverse方法翻转后,列表的结果是:{mylist}")
# 7. 删除某元素在列表中的第一个匹配项
mylist = ["itcast", "itheima", "itcast", "itheima", "python"]
mylist.remove("itheima")
print(f"通过remove方法移除元素后,列表的结果是:{mylist}")
...@@ -11,13 +11,21 @@ def list_while_func(): ...@@ -11,13 +11,21 @@ def list_while_func():
mylist = ["传智教育", "黑马程序员", "Python"] mylist = ["传智教育", "黑马程序员", "Python"]
# 循环控制变量:通过下标索引来控制,默认0 # 循环控制变量:通过下标索引来控制,默认0
# 每一次循环将下标苏姚 # 每一次循环将下标苏姚
index = 0
while index < len(mylist):
print(mylist[index])
index += 1
# list_while_func()
def list_for_func(): def list_for_func():
""" """
使用for循环遍历列表的演示函数 使用for循环遍历列表的演示函数
:return: :return:
""" """
mylist = ["传智教育", "黑马程序员", "Python"]
for e in mylist:
print(e)
list_for_func()
...@@ -38,3 +38,8 @@ print(f"字符串{my_str}中it出现的次数是:{count}") ...@@ -38,3 +38,8 @@ print(f"字符串{my_str}中it出现的次数是:{count}")
# 统计字符串的长度, len() # 统计字符串的长度, len()
num = len(my_str) num = len(my_str)
print(f"字符串{my_str}的长度是:{num}") print(f"字符串{my_str}的长度是:{num}")
my_str = "12itheima and itcast21"
new_my_str = my_str.strip("231")
print(f"字符串{my_str}被strip('12')后,结果:{new_my_str}")
\ No newline at end of file
""" """
演示对序列进行切片操作 演示对序列进行切片操作
""" """
# 对list进行切片,从1开始,4结束,步长1 # 对list进行切片,从1开始,4结束,步长1
my_list = [0, 1, 2, 3, 4, 5, 6] my_list = [0, 1, 2, 3, 4, 5, 6]
result1 = my_list[1:4] # 步长默认是1,所以可以省略不写 result1 = my_list[1:4] # 步长默认是1,所以可以省略不写
print(f"结果1:{result1}") print(f"结果1:{result1}")
# 对tuple进行切片,从头开始,到最后结束,步长1 # 对tuple进行切片,从头开始,到最后结束,步长1
my_tuple = (0, 1, 2, 3, 4, 5, 6) my_tuple = (0, 1, 2, 3, 4, 5, 6)
result2 = my_tuple[:] # 起始和结束不写表示从头到尾,步长为1可以省略 result2 = my_tuple[:] # 起始和结束不写表示从头到尾,步长为1可以省略
print(f"结果2:{result2}") print(f"结果2:{result2}")
# 对str进行切片,从头开始,到最后结束,步长2 # 对str进行切片,从头开始,到最后结束,步长2
my_str = "01234567" my_str = "01234567"
result3 = my_str[::2] result3 = my_str[::2]
print(f"结果3:{result3}") print(f"结果3:{result3}")
# 对str进行切片,从头开始,到最后结束,步长-1 # 对str进行切片,从头开始,到最后结束,步长-1
my_str = "01234567" my_str = "01234567"
result4 = my_str[::-1] # 等同于将序列反转了 result4 = my_str[::-1] # 等同于将序列反转了
print(f"结果4:{result4}") print(f"结果4:{result4}")
# 对列表进行切片,从3开始,到1结束,步长-1 # 对列表进行切片,从3开始,到1结束,步长-1
my_list = [0, 1, 2, 3, 4, 5, 6] my_list = [0, 1, 2, 3, 4, 5, 6]
result5 = my_list[3:1:-1] result5 = my_list[3:1:-1]
print(f"结果5:{result5}") print(f"结果5:{result5}")
# 对元组进行切片,从头开始,到尾结束,步长-2 # 对元组进行切片,从头开始,到尾结束,步长-2
my_tuple = (0, 1, 2, 3, 4, 5, 6) my_tuple = (0, 1, 2, 3, 4, 5, 6)
result6 = my_tuple[::-2] result6 = my_tuple[::-2]
print(f"结果6:{result6}") print(f"结果6:{result6}")
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册