TypeError:类型为'int'的参数不可迭代

时间:2012-06-25 07:02:45

标签: python linux

#!/usr/bin/python 

import time 
from array import *

THINKING  = 0
HUNGRY = 1
EATING = 2

class Philosopher: 
    def __init__(self):
        self.ph = array('i',[1, 2, 3, 4, 5])
        self.sleeptime = array('i',[30, 30, 30, 30, 30])

    def initialization_code(self):
        for i in range(self.ph.__len__()):
            self.ph[i] = THINKING

    def pickup(self,i):
        self.ph[i] = HUNGRY 
        self.test(i)
        if(EATING not in (self.ph[i])):
            while(EATING not in (self.ph[i])):
                time.sleep(self.sleeptime[i])

    def putdown(self,i):
        self.ph[i] = THINKING
        self.test((i+4)%5)
        self.test((i+1)%5)

    def test(self,i):
        if((2 not in (self.ph[(i+4)%5]))and(2 not in (self.ph[(i+1)%5]))and(self.ph[i]==HUNGRY)):
            self.ph[i] = EATING

    def start_process(self):
        for i in range(self.ph.__len__()):
            self.pickup(i)
            self.putdown(i)


    def display_status(self):
        for i in range(self.ph.__len__()):
            if (self.ph[i] == 0):
                print "%d is THINKING" % i+1
            elif (self.ph[i] == 1):
                print "%d is WAITING" % i+1
            elif (self.ph[i] == 2):
                print "%d is EATING" % i+1

phil = Philosopher()
phil.initialization_code()
phil.start_process()
phil.display_status()   

以上是我的代码片段,其中我试图在python中实现餐饮哲学家问题。 当我运行此代码时,它会向我显示此错误:

Traceback (most recent call last):

File "dining.py", line 59, in <module>

phil.start_process()

   File "dining.py", line 43, in start_process    
   self.pickup(i)    
   File "dining.py", line 27, in pickup    
   self.test(i)    
   File "dining.py", line 38, in test    
   if((2 not in (self.ph[(i+4)%5]))and(2 not in (self.ph[(i+1)%5]))and(self.ph[i]==HUNGRY)):
   TypeError: argument of type 'int' is not iterable

有人可以帮助我吗,为什么会出现这个错误。我搜索了一下但无法解决。    在此先感谢!!

3 个答案:

答案 0 :(得分:6)

你的方程导致整数。你不能在整数上使用in

>>> 'foo' in 3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: argument of type 'int' is not iterable

答案 1 :(得分:2)

除了in的问题,它只能应用于迭代和类定义中有__contains__的对象,你可能会遇到下一个问题:你没有并行化。所以你应该使用线程或替换

if(EATING not in (self.ph[i])):
    while(EATING not in (self.ph[i])):
        time.sleep(self.sleeptime[i])

行 - 这是一个无限循环,因为没有人设置EATING状态。

或者你应该通过其他方式,通过不断检查挂钟时间或创建一个事件调度系统来处理时间,这个系统负责必须完成的操作。

顺便说一句:print "%d is THINKING" % i+1也被打破了,因为()周围没有i+1%的优先级更高。

答案 2 :(得分:1)

我认为你一般都在使用:

in / not in

不正确。看起来你试图比较应该用

完成的整数
==
!=
>
>=
<
<=

运营商。