【问题标题】:Simplifying Data with a for loop (Python)使用 for 循环简化数据 (Python)
【发布时间】:2010-11-07 17:15:26
【问题描述】:

我试图简化代码:

            header = []
            header.append(header1)
            header.append(header2)                
            header.append(header3)
            header.append(header4)
            header.append(header5)
            header.append(header6)

地点:

            header1 = str(input.headerOut1)
            header2 = str(input.headerOut2)
            header3 = str(input.headerOut3)
            header4 = str(input.headerOut4)
            header5 = str(input.headerOut5)
            header6 = str(input.headerOut6)

我曾想使用 for 循环,例如:

   headerList = []
   for i in range(6)
          headerList.append(header+i) 

然而,python 不会识别 header+i 代表字符串 header1。有什么方法可以简化此代码或让 for 循环工作?非常感谢!

【问题讨论】:

  • 有人对如何标记此问题有疑问。我们需要“for”、“loop”和“simplify”吗?

标签: python string loops for-loop simplify


【解决方案1】:

您应该真正将数据构造为列表或字典,如下所示:

input.headerOut[1]
input.headerOut[2]
# etc.

这将使这更容易,更 Pythonic。但是你可以使用getattr做你想做的事:

headerList = []
for i in range(1, 7):
    header = str(getattr(input, 'headerOut%d' % i))
    headerList.append(header)

【讨论】:

  • ...如果使用列表,第一个将是 input.headerOut[0]。
  • 同意@JohnPirie,+1,因为有许多新颖的答案,但只有一个可以产生易于理解的代码。
【解决方案2】:
header = [str(getattr(input, "headerOut%d" % x)) for x in range(1,7)]

【讨论】:

    【解决方案3】:

    将标题放入一个数组并循环遍历它。

    【讨论】:

      【解决方案4】:

      您可以使用locals 将本地范围作为字典获取:

      headerList = []
      for i in xrange(1, 7):
          headerList.append(locals()['header%s' % (i,)])
      

      但是,如果可能,您应该直接使用 input 变量,正如其他一些答案所建议的那样。

      【讨论】:

      • 我对此有一个简短的问题,我以前从未见过 % (i,)。它究竟是做什么的?谢谢!
      • 是字符串格式化操作符。在此处查看文档:python.org/doc/lib/typesseq-strings.html
      猜你喜欢
      • 1970-01-01
      • 2021-08-25
      • 1970-01-01
      • 1970-01-01
      • 2012-06-23
      • 1970-01-01
      • 2022-01-25
      • 2018-04-11
      • 2016-03-06
      相关资源
      最近更新 更多