How can I evaluate variable to another variable be

2019-02-20 13:03发布

This question broken into subquestions:

  • Pointers in Python suggested by one reply to look at, more here
  • "why not to modify locals?" -question here.

Original Question

#!/usr/bin/python
#
# Description: trying to evaluate array -value to variable before assignment
# but it overwrites the variable
#
# How can I evaluate before assigning on the line 16?

#Initialization, dummy code?
x=0
y=0

variables = [x, y]
data = ['2,3,4', '5,5,6']

# variables[0] should be evaluted to `x` here, i.e. x = data[0], how?
variables[0] = data[0]

if ( variables[0] != x ):
 print("It does not work, why?");
else:
 print("It works!");

Goal: to fix hard-coded assignments on a lab-report, before I can use list-comprehensions more effectively I need to fix the assignment problem -- or am I doing something wrong?

#!/usr/bin/python
#
# Description: My goal is to get the assignments on the line 24 not-hard-coded

variables = [y, x, xE]
files = [measurable, time, timeErr]

# PROBLEM 1: Assignment problem
#
#Trying to do:
#
# var[1] = files[1] so that  if (y == measurable): print("it works")
# var[2] = files[2] so that  if (x == time): print("it works")


#GOAL TO GET ASSIGNMENT LIKE, data is in files "y, x, xE":
# 
# y = [3840,1840,1150,580,450,380,330,340,340,2723]
# x = [400.0,204.1,100.0,44.4,25.0,16.0,11.1,8.2,7.3,277.0]
# xE = [40, 25, 20, 20, 20, 20, 20, 20, 20, 35]


#Trying to do this
# 
# y = open('./y').read();
# x = open('./x').read();
# xE= open('./xE').read();
# 
# like this? f evaluated each time?
for f in files:
 f = open('./'+f).read()

7条回答
戒情不戒烟
2楼-- · 2019-02-20 13:47

...ah, I think I get what you want. There is a 99% probability that this is not a good idea, but I will give you the code to do what I think you're asking for anyway:

First you need to change this line:

variables = ['x','y']

(since you want the variable names here, not the values)

Now in order for the variable x to be assigned, one way to do that is:

locals()[variables[0]] = data[0]
查看更多
登录 后发表回答