0

如果我们能够在不使用 range 函数的情况下创建一个 for 循环,如下所示:

foods = [potato, pizza, spinach]

for food in foods:
  print(food)

为什么我不能在下面的嵌套 for 循环中做同样的事情?

def exponents(bases, powers):
  results = []

  for i in range(len(bases)):
    for j in range(len(powers)):
      results.append(bases[i]**powers[j])
  return results

而是使用这种方法:

def exponents(bases, powers):
  results = []

  for i in bases:
    for j in powers:
      results.append(bases[i]**powers[j])
  return results

将导致 indexError:

IndexError: list index out of range

关于这些变量,单循环和嵌套循环之间有什么区别?

4

1 回答 1

1

When you use the range function, you are iterating the list index. When you use the list directly, you are iterating the objects in the list.

Try this:

def exponents(bases, powers):
  results = []

  for b in bases:
    for p in powers:
      results.append(b**p)
  return results  # not new
于 2020-09-07T00:13:28.147 回答