Python-可变类型、不可变类型和遍历列表

1.可变类型和不可变类型

  • python的类型根据值是否可变分为两类

  • 可变类型:列表、字典、集合等 值可以改变

  • 不可变类型:数字、字符串、元组等 值不可以改变

注意:可变类型对象和不可变类型对象都不能更改类型本身

2.遍历列表

2.1正序遍历

  • 提前通过len函数获取元素总数,然后从0开始循环至元素总数-1

# 遍历列表的所有元素(提前获取元素总数)
x = ['John', 'George', 'Paul', 'Ringo']

for i in range(len(x)):
    print(i, x[i])
  • 使用enumerate函数成对取出索引和元素,然后进行循环

使用enumerate函数遍历列表的所有元素
x = ['John', 'George', 'Paul', 'Ringo']
for i, name in enumerate(x):
    print(i, name)
  • 使用enumerate函数成对取出索引和元素,然后进行循环(从1开始计数)

使用enumerate函数遍历列表的所有元素(从1开始计数)
x = ['John', 'George', 'Paul', 'Ringo']
for i, name in enumerate(x, 1):
    print(i, name)
  • 遍历列表的所有元素(不使用索引值)

# 遍历列表的所有元素(不使用索引值)
x = ['John', 'George', 'Paul', 'Ringo']
for i in x:
    print(i)

2.2逆序遍历

  • 利用分片实现逆序遍历

# 反向遍历并输出字符串内的所有字符
x = ['John', 'George', 'Paul', 'Ringo']
for i in x[::-1]:
    print(i)
  • 使用函数enumerate反向遍历并输出字符串内的所有字符

x = ['John', 'George', 'Paul', 'Ringo']
for i, name in enumerate(reversed(x)):
    print(i, name)
  • 使用函数enumerate反向遍历并输出字符串内的所有字符(从1开始)

x = ['John', 'George', 'Paul', 'Ringo']
for i, name in enumerate(reversed(x), 1):
    print(i, name)

注意:

将x修改为字符串x ='JohnGeorgePaulRingo'、元组x = ('John', 'George', 'Paul', 'Ringo')和集合x = {'John', 'George', 'Paul', 'Ringo'},可以实现对字符串、元组和集合的遍历

猜你喜欢

转载自blog.csdn.net/aaaccc444/article/details/129128304