Python: list items are not changed in for loop

前端 未结 3 2030
無奈伤痛
無奈伤痛 2020-12-12 07:33

I was shocked when the following code did not do what I expected it to do:

lines_list = [\'this is line 1\\n\', \'this is line 2\\n\', \'this is line 3\\n\']         


        
3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-12 08:26

    You can go through by index and modify in place that way

    for i, _ in enumerate(lines_list):
        lines_list[i] = lines_list[i].strip()
    

    though I think many would prefer the simplicity of duplicating the list if the list isn't so big that it causes an issue

    lines_list = [line.strip() for line in lines_list]
    

    The issue is using the = operator reassigns to the variable line, it doesn't do anything to affect the contents of the original string. New python programmers are equally as often surprised when:

    for i in range(10):
        print(i)
        i += 1
    

    prints the numbers 0,1,2,3,4,5,6,7,8,9. This occurs because the for loop reassigns i at the beginning of each iteration to the next element in the range. It's not exactly your problem, but it's similar.

    Since you are reading lines out of a file, and stripping them afterwards, really what you should do is

    with open(file_name) as f:
        lines_list = [line.strip() for line in f]
    

    which reads and strips one line at a time, rather than reading everything first, then stripping the lines afterwards

提交回复
热议问题