为循环和IF政治家组合的python方法

2024-04-26 20:42:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道如何在单独的行上同时使用for循环和if语句,例如:

>>> a = [2,3,4,5,6,7,8,9,0]
... xyz = [0,12,4,6,242,7,9]
... for x in xyz:
...     if x in a:
...         print(x)
0,4,6,7,9

我知道,当语句很简单时,我可以使用列表理解来组合这些语句,例如:

print([x for x in xyz if x in a])

但我在任何地方都找不到一个很好的例子(可以复制和学习)来演示一组复杂的命令(不仅仅是“print x”),这些命令是在for循环和一些if语句的组合之后出现的。我期待的是:

for x in xyz if x not in a:
    print(x...)

难道这不是python的工作方式吗?


Tags: in命令列表forif地方方式not
3条回答

您可以这样使用generator expressions

gen = (x for x in xyz if x not in a)

for x in gen:
    print x

根据The Zen of Python(如果您想知道您的代码是否是“Pythonic”,那是要去的地方):

  • 美胜于丑。
  • 显式比隐式好。
  • 简单胜于复杂。
  • 平的比嵌套的好。
  • 可读性很重要。

得到两个^{}s的^{}^{}的python方法是:

>>> sorted(set(a).intersection(xyz))
[0, 4, 6, 7, 9]

或者那些xyz但不在a中的元素:

>>> sorted(set(xyz).difference(a))
[12, 242]

但是对于一个更复杂的循环,您可能希望通过迭代一个命名良好的generator expression和/或调用一个命名良好的函数来将其展平。试图把所有的东西都放在一条线上很少是“Python式的”。


对您的问题和接受的答案更新以下附加评论

我不知道你想用^{}做什么,但是如果a是一个字典,你可能想使用这些键,比如:

>>> a = {
...     2: 'Turtle Doves',
...     3: 'French Hens',
...     4: 'Colly Birds',
...     5: 'Gold Rings',
...     6: 'Geese-a-Laying',
...     7: 'Swans-a-Swimming',
...     8: 'Maids-a-Milking',
...     9: 'Ladies Dancing',
...     0: 'Camel Books',
... }
>>>
>>> xyz = [0, 12, 4, 6, 242, 7, 9]
>>>
>>> known_things = sorted(set(a.iterkeys()).intersection(xyz))
>>> unknown_things = sorted(set(xyz).difference(a.iterkeys()))
>>>
>>> for thing in known_things:
...     print 'I know about', a[thing]
...
I know about Camel Books
I know about Colly Birds
I know about Geese-a-Laying
I know about Swans-a-Swimming
I know about Ladies Dancing
>>> print '...but...'
...but...
>>>
>>> for thing in unknown_things:
...     print "I don't know what happened on the {0}th day of Christmas".format(thing)
...
I don't know what happened on the 12th day of Christmas
I don't know what happened on the 242th day of Christmas

我个人认为这是最漂亮的版本:

a = [2,3,4,5,6,7,8,9,0]
xyz = [0,12,4,6,242,7,9]
for x in filter(lambda w: w in a, xyz):
  print x

编辑

如果您非常想避免使用lambda,那么可以使用部分函数应用程序并使用operator模块(它提供大多数运算符的函数)。

https://docs.python.org/2/library/operator.html#module-operator

from operator import contains
from functools import partial
print(list(filter(partial(contains, a), xyz)))

相关问题 更多 >