【问题标题】:Is it possible to convert a variable as a string? [duplicate]是否可以将变量转换为字符串? [复制]
【发布时间】:2014-03-07 10:54:08
【问题描述】:

我有一个列表,我想将其转换为字典。

  L =   [ 
       is_text, 
       is_archive, 
       is_hidden, 
       is_system_file, 
       is_xhtml, 
       is_audio, 
       is_video,
       is_unrecognised
     ]

有没有办法做到这一点,我可以通过程序转换成这样的字典吗:

{
    "is_text": is_text, 
    "is_archive": is_archive, 
    "is_hidden" :  is_hidden
    "is_system_file": is_system_file
    "is_xhtml": is_xhtml, 
    "is_audio": is_audio, 
    "is_video": is_video,
    "is_unrecognised": is_unrecognised
}

这里的变量是布尔值。

这样我就可以轻松地将这个字典传递给我的函数

def updateFileAttributes(self, file_attributes):
    m = models.FileAttributes(**file_attributes)
    m.save()

【问题讨论】:

  • 变量只是对对象的引用,没有办法打印变量的名称。
  • 你不是第一个问这个的人。我发现至少 3 个重复项(搜索字符串:“python 变量作为字符串”
  • 为什么需要这样做?
  • @Blender:我已经更新了我的问题,为什么我需要它,请检查!
  • 最好的方法是一开始就不将它们作为变量。或者使它们成为某个对象的属性。

标签: python


【解决方案1】:

将变量放入列表后无法获取其名称,但可以这样做:

In [211]: is_text = True

In [212]: d = dict(is_text=is_text)
Out[212]: {'is_text': True}

请注意,d 中存储的值在创建后是布尔常量,您无法通过更改变量 is_text 来动态更改 d['is_text'] 的值,因为布尔值是不可变的。

在您的情况下,您不必将file_attributes 设为复合数据结构,只需将其设为关键字参数

def updateFileAttributes(self, **file_attributes):
    m = models.FileAttributes(**file_attributes)
    m.save()

那么你可以这样调用函数:

yourObj.updateFileAttributes(is_text=True, ...)

【讨论】:

  • 我喜欢dict(is_text=is_text) 把戏,它使用**kargv 对吗?
  • @GrijeshChauhan 为什么不呢?很抱歉没能抓住你……
【解决方案2】:

我在这里做了一些假设来得出这个结果。 List 中的变量是作用域中唯一可用的 bool 变量。

{ x:eval(x) for x in dir() if type(eval(x)) is bool }

或者如果您已为变量强制执行命名约定

{ x:eval(x) for x in  dir() if x.startswith('is_') }

【讨论】:

    【解决方案3】:

    以下代码有效。

    将变量转换为字符串

    >>> a = 10
    >>> b =20
    >>> c = 30
    >>> lst = [a,b,c]
    >>> lst
    [10, 20, 30]
    >>> {str(item):item for item in lst}
    {'10': 10, '30': 30, '20': 20}
    

    仅适用于字符串。

        >>> lst = ['a','b','c']
        >>> lst
        ['a', 'b', 'c']
        >>> {item:item for item in lst}
        {'a': 'a', 'c': 'c', 'b': 'b'}
    

    【讨论】:

    • 您的列表包含字符串,而问题列表包含变量。这不是所要求的。
    • anuragal:同样的概念也适用于变量。
    • 请仔细阅读问题
    • 感谢 Anuragal 根据问题更新答案,希望现在更有意义
    • @PavanGupta:不,这会返回给你{'10':10, '20':20, ...}。但我想要{"a":10, "b":20, ...}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-03
    • 1970-01-01
    • 2017-09-12
    • 1970-01-01
    • 2019-06-03
    • 1970-01-01
    相关资源
    最近更新 更多