【发布时间】:2018-11-21 22:41:03
【问题描述】:
给定颜色列表:
colors = ["blue","brown","red","yellow","green"]
1.
for color in colors:
2.
for index in range(len(colors)):
使用 1 和 2 有什么区别?
【问题讨论】:
-
运行每一行时你得到相同的结果吗?如果没有,那就是你的区别。
给定颜色列表:
colors = ["blue","brown","red","yellow","green"]
1.
for color in colors:
2.
for index in range(len(colors)):
使用 1 和 2 有什么区别?
【问题讨论】:
当您说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"
【讨论】:
for index, color in enumerate(colors)获得两者
使用第一个,您将可以在循环中访问局部变量颜色。它也被认为更pythonic。
使用第二个,您将可以访问索引,这可能很有用。
我不知道性能差异,但可能有人知道。
【讨论】:
假设您要将列表中的每个字符串更改为大写。如果使用第一种方法,列表中的每一项基本上都会复制到临时变量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']
【讨论】: