如果我们能够在不使用 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
关于这些变量,单循环和嵌套循环之间有什么区别?