python:for循环修改list的值,应使用range

菜鸟教程list列表:https://www.runoob.com/python/python-lists.html

在for循环中直接更改列表中元素的值不会起作用,要使用range来修改

示例代码:

  • 直接使用for循环修改list的值,修改失败
  • 使用for+range修改list的值,修改成功
#一个列表
str_centence_list = [ "apple", " banana", " pear", " grape"]


#方法1:使用for循环直接改,这种方法错误,改不了list的值
for s_str in str_centence_list[1:]:  # python 从list列表的第2个元素开始遍历
    s_str = s_str.strip(' ')          # 使用python内置函数strip,去掉元素的首位空格(s_str = '  Hello world!  ')
for s_str in str_centence_list[1:]:  # 查看list中的值是否修改成功
    print(s_str)

'''
输出结果为: (元素前面的空格没有去掉,说明没有修改成功)
 banana
 pear
 grape
'''


#方法2:使用range修改,这种方法可以成功修改list的值
for i in range(len(str_centence_list)):   # 遍历list中的每一个值
    str_centence_list[i] = str_centence_list[i].strip(' ')   # 使用python内置函数去掉首位空格(s_str = '  Hello world!  ')
for i in range(len(str_centence_list)):   # 查看list中的值是否修改成功
    print(str_centence_list[i])

'''
输出结果为:
apple
banana
pear
grape
'''

参考:

https://www.cnblogs.com/lichuang/archive/2018/08/17/9492821.html   Python在for循环中更改list值的方法

Guess you like

Origin blog.csdn.net/weixin_39450145/article/details/120008293