python - 使用 exec 进行变量赋值是Pythonic吗?

标签 python python-3.x list design-patterns exec

考虑这段代码:

self._t10_test = None
self._t20_test = None
self._t30_test = None

id_lst = ['10', '20', '30']
msg_lst = ['Message for A', 'Message for B', 'Message for C')

在这种情况下使用 exec 是否正确?

for id, msg in zip(id_lst, msg_lst):
    exec((f'self._t{id}_test = {msg}')

或者这会更Pythonic吗?

for id, msg in zip(id_lst, msg_lst):
    set_msg(id, msg)


def set_msg(id, msg):
    if id == '10':
        self._t10_test = msg
    elif id == '20':
        self._t20_test = msg
    elif id == '30':
        self._t30_test = msg

最佳答案

使用exec()总是一个坏主意。我发现,如果您认为需要变量名中的变量,更好的选择是使用 dictionary 。举个例子:

self._t_test = {'10': None,
                '20': None,
                '30': None}

id_lst = ['10', '20', '30']
msg_lst = ['Message for A', 'Message for B', 'Message for C']


for i, msg in zip(id_lst, msg_lst):
    self._t_test[i] = msg

这给了我们:

>>> self._t_test
{'10': 'Message for A', '20': 'Message for B', '30': 'Message for C'}
>>> self._t_test['10']
'Message for A'

您甚至可以使用字典理解:

>>> self._t_test = {k: v for k, v in zip(id_lst, msg_lst)}
>>> self._t_test
{'10': 'Message for A', '20': 'Message for B', '30': 'Message for C'}

关于python - 使用 exec 进行变量赋值是Pythonic吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60113293/

相关文章:

python - 日期差异出现错误 - Python

python - 捕获python中全局变量值的变化

python-3.x - 将盈透证券 API 引入 Pandas

python - 如何将 "0 days 00:09:06.633000000"对象转换为分钟/小时/秒?

python - 将描述符方法的实例参数绑定(bind)到调用对象实例

python - Celery 和 Redis 后端的问题

python - 获取Python模块属性的名称和类型

python - 通过列表理解进行 7 张牌扑克手牌检测中的 5 张牌顺子

python - 如何压缩两个不同大小的列表?

java - 迭代列表直到列表为空