【问题标题】:python string split mystery IndexErrorpython字符串拆分之谜IndexError
【发布时间】:2012-09-07 16:50:34
【问题描述】:

好吧……这对我来说是个谜 下面的代码打印:

['03:20:01', 'PM', '262144', '16176136', '98.41', '547744', '11459404', '2096128',   '312', '0.01', '0']
['12:30:01', 'PM', '261748', '16176532', '98.41', '547600', '11459084', '2096128', '312', '0.01', '0']
['10:50:11', 'PM', '257516', '16180764', '98.43', '548064', '11460312', '2096128', '312', '0.01', '0']

但是当我尝试打印 c[2] 时,它给了我:

IndexError: list index out of range

我错过了什么?

代码看起来很简单

cmd = 'sar -r -f /xactly/apps/sar/sjcxtlycomp22s/sa05 |sort -g -k4' 
high = subprocess.Popen([cmd],
      stdin=subprocess.PIPE,
      stdout=subprocess.PIPE,
      stderr=subprocess.PIPE,
        shell=True)

memuse = False
count = 0 

sep = re.compile('[\s]+')
for line in high.stdout:
    if line:
        line = line.strip()
        count += 1
        c = sep.split(line)
        print c

【问题讨论】:

  • 除了print c 之外,您能否添加len(c),让我们知道您看到了什么?
  • 您将print c[2] 声明放在哪里? (另外,这不是您的问题,您是否知道 re 在这里有点矫枉过正,因为字符串有一个 .split() 方法默认在空格上拆分?)
  • @Wooble,c[2]c = sep.split(line)之后打印的代码和错误非常明显。否则,索引错误不会知道c 是一个列表。此外,如果他在循环之后打印它,则 c 的最后一个值(将是一个列表)将被保留。
  • 已修复 ... 添加了“if count > 3:” ...我需要跳过前三行。
  • @GodMan:很明显 OP 在输出上撒谎,那么为什么不对错误消息和代码撒谎呢? (投票结束,因为过于本地化)

标签: python list indexing range


【解决方案1】:

我需要跳过前三行数据,所以我修改了它:

sep = re.compile('[\s]+')
   for line in high.stdout:
       if line:
           line = line.strip()
           count += 1
           if count > 3:
               c = sep.split(line)
               print c[4]

【讨论】:

  • 如果这能解决您的问题,请接受您自己的答案,以便我们继续前进。
  • 不幸的是我要等两天:(
猜你喜欢
  • 2011-03-23
  • 2023-04-06
  • 2010-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多