python - 如何在分配之前将变量评估为另一个变量?

标签 python variable-assignment

<分区>

这个问题分成子问题:

  • Python 中的指针由一个回复建议查看,更多 here
  • “为什么不修改局部变量?” -问题here.

原始问题

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

最佳答案

我会使用带有一些间接性的字典。当你想使用动态变量名时,这会提示你不应该使用实际变量,而应该使用某种数据结构,如列表或字典。

尝试使用两种数据结构:一个名为 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()

关于python - 如何在分配之前将变量评估为另一个变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4590407/

相关文章:

python - 如何将零向量添加到 Pandas DataFrame?

python - 错误 - 值错误 : invalid literal for int() with base 10: ' '

Python 和多处理示例

c# - 数据完整性问题C#

结构中的 C 2 维字符

matlab - 如何将向量(沿第四维)分配给预先指定的下标

c - 为什么 "a && (b = 5/a)"不将 "5/a"分配给 "b"?

python - Jinja2 异常处理

python - django Rest框架如何删除多余的查询?

java - 在Java中,为什么map.get(key)[0]作为左侧有效,而map.get(key)则无效?