How to use python3 for-zip and how to store values in objects.

Asked 2 years ago, Updated 2 years ago, 39 views

I am having trouble using the for statement in python3.
Pour the list into the for statement into one function and put the calculated results into different objects. I want to save it, but it doesn't work.I am not an engineer, so
I'm sorry that the questioning method may be inappropriate, but I appreciate your cooperation.
Below is the code.

def test(x):
    x
    return x

test_list=['1', '2', '3', '4', '5']
x = test_list
test_df = [df1, df2, df3, df4, df5 ]
y = test_df

for i1, i2 in zip(x,y):
    y = test(x)
df1

I want to store '1', '2', '3', '4', and '5' in df1, df2, df3, df4, and df5 respectively

python python3

2022-09-30 21:30

2 Answers

You can save it to different objects by writing the following:

test_list=['1', '2', '3', '4', '5']
test_df = ['df1', 'df2', 'df3', 'df4', 'df5' ]
for x, yin zip(test_list, test_df):
    exec(y+"='+x+"")

Also, I think it would be easier to understand if you use it as a list or use a dictionary type to create a dictionary as follows:

test_list=['1', '2', '3', '4', '5']
test_df = [1,2,3,4,5]
df = {}
for x, yin zip(test_list, test_df):
    df[y] = x

To use:

df[1]


2022-09-30 21:30

def square(num):
    return num*num;
xs = [1,2,3,4,5]

as
 df1 = 1, df2 = 4, df3 = 9, df4 = 16, df5 = 25

A state in which a variable is substituted is obtained.
At this time, if you want to write the most concisely in python, you'd better use the for, which is called the in-list notation below, and because of the technique of breaking down the list and replacing it all at once, just this line is enough to get the desired state.This time, we defined the square function as an easy-to-understand example, but the function itself is free to replace.(Even if it's not square or a test defined by the questioner, it's ok)

 df1, df2, df3, df4, df5 = [square(x) for x in xs]

Here, the image on the right side takes elements one by one from the list [1, 2, 3, 4, 5] called xs, applies the function, and stores the return value in the list.Accordingly, the right side becomes [1, 4, 9, 16, 25].
In the left side, the list of the right side is stored sequentially from the left side to obtain a result obtained.
To get a testdf, use the

test_df=[df1, df2, df3, df4, df5]# or
test_df = [square(x) for x in xs ]

If you want to do the same with a regular python for statement, you can use the following statement to get similar results.(However, I recommend it because the above writing is more efficient and short without indentation.)

test_df=[]
for x in xs:
    test_df.append(square(x))
df1, df2, df3, df4, df5 = test_df


2022-09-30 21:30

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.