【问题标题】:while loop calling array outside [closed]while循环调用外部数组[关闭]
【发布时间】:2016-07-27 10:53:03
【问题描述】:

我会重新开始,谢谢大家的回复。

我有一个日志文件,然后我获取条目并从中删除所有垃圾。 我剩下的数组或列表是这个

23
23.23.23.23
45
45.45.45.45
100
34.34.54.13

我如何调用我想要的每一行。

a = 1
while a < 18:
    a = a + 2
    #logging.debug(line.split(PID_ANDROID)[a])
    countIP = a
    trySomething()

    if a == 20:
        break

但我必须在我调用它之后做一些事情。 我希望能够使用第一个条目,

> do something 
> see if something is happening
> if its not goto 3rd entry
> try the same thing again.

这就是我所坚持的。 因为当我从其他内部调用它并使用全局存储时。 python 告诉我我不能使用 str 或 turp。或者使用下面的代码可以继续输出列表中的所有内容。

atm 我有这个代码。

def trySomething():
global countIP
global LOG_SPLITER
#logging.debug('Processing Number: %s' % (countIP,))
logging.debug(LOG_SPLITER.split(PID_ANDROID)[countIP])
time.sleep(.5)
clearScreen()
#grabBox90()
#lineGoto()

我的问题是。 我怎样才能循环,一次只拉出一个来做某事,当我完成循环时转到下一个?

【问题讨论】:

  • c = + 2 不是有效的 Python,我还建议您开始使用 x+=1 之类的东西,而不是 x = x + 1
  • 这篇文章确实需要改进,以便您提出一个明确的问题和问题。就目前而言,这似乎更像是在胡扯你的工作。

标签: python loops if-statement for-loop while-loop


【解决方案1】:

看起来您应该使用初始索引为 1 且步长为 2 的 for 循环。或者,对值 1 使用显式调试语句,然后从 3 开始循环其余部分,以避免如果测试。如果代码的其余部分是递增 1 而不是 2,那么这允许您在仍然有循环的同时正确地执行初始跳过。

代替

c = 1
#do my stuff
while c < 20:
    if c == 1:
        logging.debug(line.split(PID_ANDROID)[c])
        c = + 2
    else:
        logging.debug('Moving on to a refresh')
    # You do not incremennt c
    # c += 2 should go here to increment every time

Python 2

for i in xrange(1,20,2):
  # do your processing

Python 3

for i in range(1,20,2):
  # do you processing

【讨论】:

  • 完美参考,我在循环中添加了代码并将其他所有内容移到了外面。
  • 代码有效,对于想知道我想要实现的目标的每个人来说都是这样。 a = 1 而 a
【解决方案2】:

如果您只是想记录line 中的每个条目,您可以这样做:

entries = line.split(PID_ANDROID)
for e in entries[::2]:  # take every other element
    logging.debug(e)

遍历条目是“更pythonic”。

【讨论】:

  • 由于他在c==1 上明确调试并跳过所有其余部分,这不是他所要求的。
猜你喜欢
  • 2013-11-30
  • 1970-01-01
  • 1970-01-01
  • 2015-12-26
  • 2016-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-25
相关资源
最近更新 更多