如何访问for循环内的元素?

时间:2019-12-22 21:05:45

标签: python arrays for-loop

我对Python完全陌生。我正在尝试使用此代码访问和打印数组的 ith 元素。

import time
from random import random

array = []
array1 = []

a = 0

for i in range(1,100000000):
    a = a + 1
    time.sleep(.2)

    x = random()

    array.append(x)
    #print(array)
    array1[a] = array[a]*0.5

    print(array[a])

但是它给了我这个错误:

Traceback (most recent call last):
  File "C:/Users/carlo/.PyCharmCE2019.3/config/scratches/PaulMcW(Plotting)/StoringData.py", line 17, in <module>
    array1[a] = array[a]*0.5
IndexError: list index out of range

如何执行此简单任务?

3 个答案:

答案 0 :(得分:3)

您正试图访问列表中不存在的成员。

a = a + 1
time.sleep(.2)

x = random()
array.append(x)
array1[a] = array[a]*0.5

print(array[a])

a等于1,但是请注意列表索引从0开始,而不是从1开始。这就是为什么您的错误显示“列表索引超出范围”。

解决方案是将a = a + 1移至for循环的末尾。

time.sleep(.2)

x = random()
array.append(x)
array1[a] = array[a]*0.5

print(array[a])
a = a + 1

但是,还有另一个问题:您正在分配array1[a] = array[a]*0.5,但是array1为空。要解决此问题,请使用与array相同的方法。

time.sleep(.2)

x = random()
array.append(x)
array1.append(array[a]*0.5)

print(array[a])
a = a + 1

答案 1 :(得分:1)

问题在于数组是从零开始的,因此array[1]在您尝试访问它时还不存在,只有array[0]。但是,您无需明确跟踪长度; array[-1]始终引用非空数组的最后一个元素。

(最小的解决方法是从a = -1开始。)

我不认为sleep会带来任何价值,所以也许也可以消除它。

for i in range(99999999):
    x = random()
    array.append(x)
    array1.append(x*0.5)
    print(array[a])

答案 2 :(得分:1)

  

我正在尝试访问和打印数组的第ith个元素...

# Declare an array that has elements

a = [1, 2, 3]

# loop over the elements, using the array's count
for i in range(0, len(a)):
    print(a[i])

# But usually we do it like this
# We can just iterate over the array and get each element directly
# We only need an index (i) if we care about the
# location of the element in the array
for el in a:
    print(el)

注意:您的代码中还有很多其他问题,但我正在尝试解决您所询问的问题。

对于初学者来说,学习的好方法通常是先用英语说出他们想做什么,然后在每个注释下编写代码(就像我在上面的代码示例中所做的那样)。摆脱其他任何事物(例如调用randomsleep等)