我有这个:
colors = ["blue","brown","red","yellow","green"]
1。
for color in colors:
2。
for index in range(len(colors)):
使用 1 和 2 有什么区别?
答案 0 :(得分:5)
您说for color in colors:
就是要遍历列表中的项目。
for color in colors:
print(color)
>>> "blue"
>>> "brown"
>>> "red"
>>> "yellow"
>>> "green"
如果遍历索引,您将得到:
for index in range(len(colors)):
print(index)
>>> 0
>>> 1
>>> 2
>>> 3
>>> 4
您可以使用enumerate
来获得两个版本:
for c, color in enumerate(colors):
print(c, color)
>>> 0 "blue"
>>> 1 "brown"
>>> 2 "red"
>>> 3 "yellow"
>>> 4 "green"
答案 1 :(得分:0)
使用第一个,您将可以在循环内访问局部变量颜色。它也被认为是更pythonic的。
使用第二个索引,您将可以访问该索引,这可能会有用。
我不了解性能差异,但有人知道。
答案 2 :(得分:0)
假设您要将列表中的每个字符串都更改为大写。如果使用第一种方法,则列表中的每个项目基本上都会复制到临时变量color
中。您可以根据需要更改color
,但这不会更改列表本身。
for color in colors:
color = color.upper()
print(colors)
>>>['blue', 'brown', 'red', 'yellow', 'green']
调用range
和len
时,可以更改列表中的项目,因为它们具有索引。
for index in range(len(colors)):
colors[index] = colors[index].upper()
print(colors)
>>>['BLUE', 'BROWN', 'RED', 'YELLOW', 'GREEN']