2012-03-28 78 views
0

我可以避免重複每個屬性名稱嗎?我可以替換這個重複的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

這裏有一個選項:

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

你錯過了在字符串格式化第三''var''。我寧願使用''format''來避免重複 – 2012-03-28 22:58:43

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