Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
475 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 Answer

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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...