“为了"python中的循环结构 [英] "For" loop structure in python
问题描述
在调试一小段代码时,我注意到了一些意想不到的事情:
As I was debugging a small bit of code, I noticed something unexpected:
循环遍历文件名以删除数字的 for 循环,通过查看字符串的每个字符并替换它,似乎打印文件名,因为它存在于循环的第一遍中并循环遍历那些字母,因此如果像我在代码中所做的那样对传递给循环的字符串进行更改,python 仍然会查找字符串中的那些字母作为开头.
The for loop that cycles through the filename to remove the numbers, by looking at each character of the string and replacing it, seems to take a print of the filename as it exists in the first pass of the loop and cycles through those letters, so that if, as I do in the code, make changes to the string passed to the loop, python still looks for those letters that were in the string to begin with.
我是否刚刚(为我自己)发现了 for 循环的一个基本特征,或者这只是我的代码导致的一些奇怪的东西?
Have I just uncovered (for myself) a fundamental feature of the for loop, or is this just something weird that resulted from my code?
short_list = ['1787cairo.jpg', '237398rochester.jpg']
print short_list
for entry in short_list:
entry_pos = short_list.index(entry)
for char in entry:
print entry, char, ord(char)
if ord(char) in range (48,58):
entry = entry.replace(char,'')
print entry
short_list[entry_pos] = entry
print short_list
推荐答案
这里的重点是 Python 变量实际上只是指向对象的名称.当您执行 for char in entry
时,for 循环将迭代 entry
恰好指向的任何内容;如果您随后重新分配 entry
以指向其他内容,则迭代器将不知道这一点.
The point here is that Python variables are really just names that point at objects. When you do for char in entry
the for loop is iterating over whatever entry
happens to point to; if you then reassign entry
to point to something else, the iterator won't know that.
注意,如果 entry
碰巧是一个可变对象,比如一个列表,并且你改变了那个对象中的项目,迭代器看到的值会改变;同样,这是因为迭代器指向对象本身.
Note that if entry
happened to be a mutable object, like a list, and you mutated the items in that object, the values seen by the iterator would change; again, this is because the iterator is pointing to the object itself.
虽然你的代码过于复杂;与其保留索引并替换列表中的项目,不如使用更改后的项目构建新列表:
Really though your code is over-complicated; rather than keeping indexes and replacing items in the list, you should be building up new lists with the changed items:
new_list = []
for entry in short_list:
new_entry = ''
for char in entry:
if ord(char) not in range (48,58):
new_entry += char
new_list.append(new_entry)
这可以进一步缩短为嵌套列表理解:
and this can be shortened further to a nested list comprehension:
[''.join(char for char in entry if ord(char) not in range (48,58)) for entry in short_list]
(并且,作为进一步的改进,您对 ord(char)
的检查可以替换为 char.isdigit()
.)
(and, as a further improvement, your check of ord(char)
can be replaced by char.isdigit()
.)
这篇关于“为了"python中的循环结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!