问题描述
当以下代码未达到我的预期时,我感到震惊:
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']
for line in lines_list:
line = line.strip()
我当然希望列表中的每个项目都变为"stripped"
,即在这种情况下,不包含尾随的'\n'
字符,但是并没有...
I of course expected each item in the list to become "stripped"
, i.e. in this case, to be free of the trailing '\n'
char, but it did not...
print lines_list
输出:
['this is line 1\n', 'this is line 2\n', 'this is line 3\n']
如您所料,我的问题是在for
循环中是否有一种优雅的方式来更改列表项?我不想重复列表...
So as you can guess, my question is if there is an elegant way to change the list items during the for
loop? I don't want to duplicate the list...
编辑:
我想提一下,在 Perl 或 Java 中,我的用法效果很好. Python是具有独特行为的人
I wanted to mention that by the way, in Perl or in Java, my usage works well. Python is the one with the unique behavior
在Java中,它将起作用:
In Java this will work:
String[] lines = {"this is line 1\n", "this is line 2\n", "this is line 3\n"};
for (String line : lines) {
line = line.trim();
}
在Perl中,它将起作用:
In Perl this will work:
my @lines = ("this is line 1\n", "this is line 2\n", "this is line 3\n");
foreach my $line (@lines) {
$line =~ s/\s+$//;
$line =~ s/^\s+//;
}
推荐答案
您可以按索引浏览并以这种方式进行修改
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]
问题是使用=
运算符重新分配给变量line
,它没有做任何事情来影响原始字符串的内容.在以下情况下,新的python程序员同样会感到惊讶:
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
打印数字0、1、2、3、4、5、6、7、8、9.发生这种情况是因为for循环在每次迭代开始时将i
重新分配给范围中的下一个元素.这不完全是您的问题,但这是相似的.
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
这篇关于Python:列表项不会在for循环中更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!