【问题标题】:What's the difference between using range() and using a for loop?使用 range() 和使用 for 循环有什么区别?
【发布时间】:2018-11-21 22:41:03
【问题描述】:

给定颜色列表:

colors = ["blue","brown","red","yellow","green"]

1.

for color in colors:
 

2.

for index in range(len(colors)):

使用 12 有什么区别?

【问题讨论】:

  • 运行每一行时你得到相同的结果吗?如果没有,那就是你的区别。

标签: python for-loop range


【解决方案1】:

当您说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)获得两者
【解决方案2】:

使用第一个,您将可以在循环中访问局部变量颜色。它也被认为更pythonic。

使用第二个,您将可以访问索引,这可能很有用。

我不知道性能差异,但可能有人知道。

【讨论】:

    【解决方案3】:

    假设您要将列表中的每个字符串更改为大写。如果使用第一种方法,列表中的每一项基本上都会复制到临时变量color。您可以根据需要更改color,但这不会更改列表本身。

    for color in colors:
        color = color.upper()
    print(colors)
    >>>['blue', 'brown', 'red', 'yellow', 'green']
    

    当您调用rangelen 时,您可以更改列表中的项目,因为您有它们的索引。

    for index in range(len(colors)):
        colors[index] = colors[index].upper()
    print(colors)
    >>>['BLUE', 'BROWN', 'RED', 'YELLOW', 'GREEN']
    

    【讨论】:

      猜你喜欢
      • 2019-10-01
      • 2011-04-01
      • 1970-01-01
      • 2013-11-18
      • 1970-01-01
      • 2021-06-28
      • 1970-01-01
      • 1970-01-01
      • 2013-11-14
      相关资源
      最近更新 更多