简体   繁体   中英

How do you alter a variable name in a loop in python?

I having trouble figuring out how to do what is probably a simple thing. I may have not have phrased the question well so i will just demonstrate what I want to do in the code below:

    x = 1
    while x != 10:
        y = x
        x = x + 1

I problem is that I want there to be a number after y, which is equal to x.

So when x = 1: y1 = 1

And when x = 2: y2 = 2

This code is the simplest way I think I can show my question but your answer will help me be able to run my code like I want to. I just want you to keep in mind that I will NOT accept this answer:

    x = 1
    while(x != 10):
        if x = 1:
            y1 = 1
        elif x = 2:
            y2 = 2
        elif x = 3:
            y3 = 3
        (etc...)

The whole purpose of this question is to avoid using the process above. I appreciate your time.

Use dictionaries:

    y = {}
    x = 1
    while x < 10:
        y[x] = x
        x += 1

    >>> y = {1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9} 

Here, you can access the different y values by their keys: y[1], y[2], etc.

Or, use lists:

    y = []
    x = 1
    while x < 10:
        y.append(x)
        x += 1    

    >>> y = [1, 2, 3, 4, 5, 6, 7, 8, 9]

Here you can access each y value using their index(starting at 0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM