2013-04-29 42 views
0

我想结合循环和逻辑操作,如下所示,并运行到编译错误。循环(条件)和逻辑操作在python

有关如何解决此问题的任何输入?

File "test.py", line 36 
    for ((num in list) and (num not in handled_list)): 
                 ^
SyntaxError: invalid syntax 
+1

你想完成什么?你不能在这样的'for'语句中使用条件表达式。 – BrenBarn 2013-04-29 06:03:46

+1

'list'是内建函数'list()'的名称,所以最好不要用它作为变量。 – 2013-04-29 06:17:09

+0

您可以使用带条件的'while'。 'for'只能用于迭代器和序列。 – 2013-04-29 06:17:39

回答

3

你也可以做到这一点使用集:

>>> a = [1, 2, 3, 4, 5] 
>>> b = [3, 5] 
>>> for num in set(a)^set(b): 
...  print num 
... 
1 
2 
4 
2

for语句不支持这种语法。语法只是for item in iterable ---你不能指定条件。指定您的条件内循环:

for num in list: 
    if num in handled_list: 
     continue 
    # Do what you want with the elements in list but not in handled_list 

或者预先创建一个列表(或其他可迭代),有要遍历什么。

0

for语句不能用那种方式。一个简单的方法来完成你想要做的可能是以下。

>>> for num in listOne: 
     if num not in listTwo: 
      # Do Something 

此外,list是一个内置的对象,它会是很好的,如果你没有使用,作为一个变量名。

1

for声明犯规允许你正在试图做的条件句。

但是,您可以检查存在:

假设如下:

nums = [1,2,3,5,4] 
handled_list = [12,3,5,23,4] 
num = 2 

if ((num in nums) and (num not in handled_list)): 
    print "hello, i did find the number in nums but not in handled list" 

迭代仍然发生在if语句,但不允许对每个迭代元素的访问。

+0

'list'对于变量名来说是一个糟糕的选择。 – 2013-04-29 06:16:33

+0

绝对同意你,我直接写下他的问题。 – 2013-04-29 06:18:18

0

试图用自己的例子尽可能紧,这是一个解决方案:

my_list = [1, 3, 5] 
handled_list = [3] 

for n in [num for num in my_list if num not in handled_list]: 
    print n 

强烈建议,以避免内建的重新定义,就像你似乎与“清单”的事情。