如何在赋值前评估变量?

1 投票
7 回答
1308 浏览
提问于 2025-04-16 09:22

这个问题分成了几个小问题:

  • 有一个回复建议在Python中查看指针,更多信息可以在这里找到。
  • 关于“为什么不修改局部变量?”的问题可以在这里查看。

原始问题

#!/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!");

目标: 在实验报告中修复硬编码的赋值,在我能更有效地使用列表推导式之前,我需要解决赋值的问题——或者说我是不是做错了什么?

#!/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 个回答

1

你对引用的基本概念有一些了解,但可能有点困惑。当你执行 variables[0] = data[0] 这条语句时,你并不是在重新指定 x 指向的内容,而是在重新指定 variables[0] 指向的内容。这就是为什么“它不起作用”的原因。

这里:

x = 0
y = x
y = 4

这正是你想要做的事情的核心。如果你把这个输入到 REPL(一个可以实时运行代码的环境)中,你会发现 x 仍然等于 0,而不是 4。

2

我建议使用一个字典,并加一点间接的方式。当你想用动态的变量名时,这其实是在提醒你,不应该使用真正的变量,而是应该用一些数据结构,比如列表或者字典。

可以尝试使用两个数据结构:一个叫 variables 的列表,用来存储变量的 名字,还有一个叫 values 的字典,用来存储它们的

variables = ['y', 'x', 'xE']
values = dict((name, None) for name in variables)
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")

values[variables[1]] = files[1]
values[variables[2]] = files[2]

if values['y'] == measurable:
    print("it works")


# GOAL TO GET ASSIGNMENT LIKE, data is in files "y, x, xE":

for name in variables:
    variables[name] = open('./'+name).read()
1

看起来你可能想得太复杂了。想想你到底想要什么样的结果。你的代码让我有点困惑,我甚至不太确定你想解决的具体问题是什么。我觉得有两种可能性(这两种看起来合理,当然还有很多不合理的情况):

  1. 你想把 x 设为 '2,3,4',y 设为 '5,5,6',但在你初始化 x 和 y 的时候并没有这些值。那你可以这样做:

    data = []
    ... data is eventually populated ...
    x, y = data
    
  2. 你想要一个字典,里面有键 x 和 y,以及来自数据的对应值,这种情况下你可以这样做:

    klist = ['x', 'y']
    data = ['2,3,4', '5,5,6']
    mydict = dict(zip(klist, data))
    # mydict['x'] == '2,3,4'
    

撰写回答