将打印输出分配给python中的变量

2024-04-24 09:05:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道如何将打印输出分配给变量。

所以如果

mystring = "a=\'12\'"

那么

print mystring 
a=12

我想把这个像克瓦格一样传过去

test(mystring)

我该怎么做?

更多的解释是:我有一个从数据文件的注释行得到的字符串列表。看起来是这样的:

"a='0.015in' lPrime='0.292' offX='45um' offY='75um' sPrime='0.393' twistLength='0'",
 "a='0.015in' lPrime='0.292' offX='60um' offY='75um' sPrime='0.393' twistLength='0'",
 "a='0.015in' lPrime='0.292' offX='75um' offY='75um' sPrime='0.393' twistLength='0'",
 '']

我想把这些值放到某种结构中,这样我就可以绘制出各种东西与任何变量的对比图,所以列表基本上是一个图例,我还想绘制出图例中给定的跟踪函数与变量的对比图。

因此,如果对于每个条目我都有一个跟踪,那么我可能想为一系列a值绘制max(trace)vs offX。

我的第一个想法是将字符串作为**kwargs传递给一个函数,该函数将生成相应数据的矩阵。


Tags: 函数字符串intest列表绘制print图例
3条回答

您可以调用python对象上的__str____repr__来获得它们的字符串表示(它们之间有一个微小的区别,所以请参阅文档)。这实际上是由print内部完成的。

重定向stdout并在对象中捕获其输出?

import sys

# a simple class with a write method
class WritableObject:
    def __init__(self):
        self.content = []
    def write(self, string):
        self.content.append(string)

# example with redirection of sys.stdout
foo = WritableObject()                   # a writable object
sys.stdout = foo                         # redirection

print "one, two, three, four"            # some writing

然后从foo.content中获取“输出”并对其执行所需的操作。

如果我误解了你的要求,请不要理会。

我个人不会那样做的。一个简单得多的解决方案是首先从数据构建字典,然后将其整体作为**kwargs传递给函数。例如(这不是最优雅的方法,但它是说明性的):

import re

remove_non_digits = re.compile(r'[^\d.]+')

inputList = ["a='0.015in' lPrime='0.292' offX='45um' offY='75um' sPrime='0.393' twistLength='0'",
 "a='0.015in' lPrime='0.292' offX='60um' offY='75um' sPrime='0.393' twistLength='0'",
 "a='0.015in' lPrime='0.292' offX='75um' offY='75um' sPrime='0.393' twistLength='0'", '']

#remove empty strings
flag = True
while flag:
    try:
        inputList.remove('')
    except ValueError:
        flag=False

outputList = []

for varString in inputList:
    varStringList = varString.split()
    varDict = {}
    for aVar in varStringList:
        varList = aVar.split('=')
        varDict[varList[0]] = varList[1]
    outputList.append(varDict)

for aDict in outputList:
    for aKey in aDict:
        aDict[aKey] = float(remove_non_digits.sub('', aDict[aKey]))

print outputList

这张照片:

[{'a': 0.014999999999999999, 'offY': 75.0, 'offX': 45.0, 'twistLength': 0.0, 'lPrime': 0.29199999999999998, 'sPrime': 0.39300000000000002}, {'a': 0.014999999999999999, 'offY': 75.0, 'offX': 60.0, 'twistLength': 0.0, 'lPrime': 0.29199999999999998, 'sPrime': 0.39300000000000002}, {'a': 0.014999999999999999, 'offY': 75.0, 'offX': 75.0, 'twistLength': 0.0, 'lPrime': 0.29199999999999998, 'sPrime': 0.39300000000000002}]

这似乎正是你想要的。

相关问题 更多 >