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

时间:2012-03-28 22:50:20

标签: python multidimensional-array for-loop

我可以避免重复每个属性名称吗?我可以替换这个重复的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)

2 个答案:

答案 0 :(得分:2)

这是一个选项:

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))

答案 1 :(得分:1)

使用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))