在分配之前如何将变量评估为另一个变量? [英] How can I evaluate variable to another variable before assigning?

查看:24
本文介绍了在分配之前如何将变量评估为另一个变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题分为子问题:

原始问题

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

推荐答案

看来您只是想多了.想想你想要的实际结果.这段代码太混乱了,我什至不确定您要解决的实际问题是什么.我看到了两种可能性之一(这似乎是合理的 - 有无数不合理的可能性):

It looks like you're just overthinking the problem. Think about what actual outcome you want to have. This code is so confused that I'm not even sure what the actual problem is you're trying to solve. I see one of two possibilities (that seem reasonable - there are infinite unreasonable ones):

  1. 您想分配 x = '2,3,4' 和 y = '5,5,6',但在初始化 x 和 y 时没有值.在这种情况下,你会这样做:

  1. You want to assign x = '2,3,4' and y = '5,5,6', but you don't have the values at the time you initialize x and y. In this case, you'd do:

data = []
... data is eventually populated ...
x, y = data

  • 你想要一个带有键 x 和 y 的字典,其中包含来自数据的相应值,在这种情况下你会这样做:

  • You want a dictionary with keys x and y with the corresponding values from data, in which case you'd do:

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

  • 这篇关于在分配之前如何将变量评估为另一个变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆