Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
479 views
in Technique[技术] by (71.8m points)

python - How can I increment array with loop?

I've got two lists:

listOne = ['33.325556', '59.8149016457', '51.1289412359']
listTwo = ['2.5929778', '1.57945488999', '8.57262235411']

I use len to tell me how many items are in my list:

itemsInListOne = int(len(listOne))
itemsInListTwo = int(len(listTwo))

Then, this is where I get stuck. I want to loop through the list using a while loop and increment the array with each loop. Here is what I tried:

iterations = 0

while iterations < itemsInListOne:
        listOne = listOne[0] + 1
        print iterations

The while loop is clearly wrong, but you can see what i'm trying to do. I want to end up with:

listOne[0]
listOne[1]
listOne[2]

Thanks in advance.

EDIT: To better explain this.

I've got a list and I want to loop through the list and automatically create an array which increments with each iteration, for example:

listOne[0] 
+1
listOne[1] 
+ 1 
listOne[2]

Hope this makes more sense.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You mean to do:

while iterations < itemsInListOne:
    listOne[iterations] = float(listOne[iterations]) + 1

Note that you needed to convert it to a float before adding to it.

Also note that this could be done more easily with a list comprehension:

listOne = [float(x) + 1 for x in listOne]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...