Python Loop: List Index Out of Range

前端 未结 4 1033
情话喂你
情话喂你 2020-11-28 15:10

Given the following list

a = [0, 1, 2, 3]

I\'d like to create a new list b, which consists of elements for which the current a

4条回答
  •  日久生厌
    2020-11-28 15:41

    Try reducing the range of the for loop to range(len(a)-1):

    a = [0,1,2,3]
    b = []
    
    for i in range(len(a)-1):
        b.append(a[i]+a[i+1])
    
    print(b)
    

    This can also be written as a list comprehension:

    b = [a[i] + a[i+1] for i in range(len(a)-1)]
    print(b)
    

提交回复
热议问题