在分配之前如何将变量评估为另一个变量? [关闭]

2023-12-07

这个问题分为子问题:

  • 一个回复建议查看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!");

Goal:要修复实验室报告上的硬编码作业,在我可以更有效地使用列表理解之前,我需要解决作业问题 - 或者我做错了什么?

#!/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其中存储了names变量和一个名为的字典values其中存储他们的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()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在分配之前如何将变量评估为另一个变量? [关闭] 的相关文章

随机推荐