如何用并行变量简化多变量for循环?

2024-09-28 20:49:48 发布

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

我可以避免重复每个属性名吗?我可以替换这个重复的2D列表吗?在

test_list = (('PointValue',  s_pt.PointValue,  m_pt.PointValue),
             ('PointType',   s_pt.PointType,   m_pt.PointType),
             ('Group',       s_pt.Group,       m_pt.Group),
             ('TimeStamp',   s_pt.TimeStamp,   m_pt.TimeStamp),
             ('Tag',         s_pt.Tag,         m_pt.Tag),
             ('PointTime',   s_pt.PointTime,   m_pt.PointTime),
             ('PointNumber', s_pt.PointNumber, m_pt.PointNumber),
             ('Quality',     s_pt.Quality,     m_pt.Quality))
for var, s_var, m_var in test_list:
  REPORT += 'Slave %s = %s ::: Master %s = %s\n' % (var, s_var, var, m_var)

Tags: testpt列表for属性vartaggroup
2条回答

使用getattr。如getattr(s_pt, 'PointValue')而不是s_pt.PointValue。在

那么你的循环将是:

test_list = ['PointValue', 'PointType', 'Group', 'TimeStamp', 
         'Tag', 'PointTime', 'PointNumber', 'Quality']

for var in test_list:
    REPORT += 'Slave {0} = {1} ::: Master {0} = {2}\n'.format(
        var, getattr(s_pt, var), getattr(m_pt, var))

这里有一个选择:

test_list = ('PointValue', 'PointType', 'Group', 'TimeStamp', 
             'Tag', 'PointTime', 'PointNumber', 'Quality')

format_string = 'Slave %s = %s ::: Master %s = %s\n'
for var in test_list:
    REPORT += format_string % (var, getattr(s_pt, var), var, getattr(m_pt, var))

相关问题 更多 >