结合 for 循环和 if 语句的 Pythonic 方式

发布于 2024-11-28 23:27:16 字数 494 浏览 1 评论 0 原文

我知道如何在单独的行上使用 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 应该工作的方式吗?

I know how to use both for loops and if statements on separate lines, such as:

>>> 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

And I know I can use a list comprehension to combine these when the statements are simple, such as:

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

But what I can't find is a good example anywhere (to copy and learn from) demonstrating a complex set of commands (not just "print x") that occur following a combination of a for loop and some if statements. Something that I would expect looks like:

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

Is this just not the way python is supposed to work?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

挽梦忆笙歌 2024-12-05 23:27:17

如果生成器表达式变得过于复杂或复杂,您也可以使用 生成器

def gen():
    for x in xyz:
        if x in a:
            yield x

for x in gen():
    print x

You can use generators too, if generator expressions become too involved or complex:

def gen():
    for x in xyz:
        if x in a:
            yield x

for x in gen():
    print x
长不大的小祸害 2024-12-05 23:27:17

基于此处的文章:https://towardsdatascience.com/a-compressive-hands-on-guide-to-transfer-learning-with-real-world-applications-in-deep-learning-212bf3b2f27a
出于同样的原因,我使用了以下代码,并且运行得很好:

an_array = [x for x in xyz if x not in a]

这一行是程序的一部分!这意味着 XYZ 是一个要预先定义和分配的数组,也是变量 a

使用生成器表达式(在所选答案中推荐)会产生一些困难,因为结果不是一个数组

based on the article here: https://towardsdatascience.com/a-comprehensive-hands-on-guide-to-transfer-learning-with-real-world-applications-in-deep-learning-212bf3b2f27a
I used the following code for the same reason and it worked just fine:

an_array = [x for x in xyz if x not in a]

This line is a part of the program! this means that XYZ is an array which is to be defined and assigned previously, and also the variable a

Using generator expressions (which is recommended in the selected answer) makes some difficulties because the result is not an array

手长情犹 2024-12-05 23:27:17

使用 intersectionintersection_update

  • intersection

    <前><代码>a = [2,3,4,5,6,7,8,9,0]
    xyz = [0,12,4,6,242,7,9]
    ans = 排序(set(a).intersection(set(xyz)))

  • intersection_update

    <前><代码>a = [2,3,4,5,6,7,8,9,0]
    xyz = [0,12,4,6,242,7,9]
    b = 集合(a)
    b.intersection_update(xyz)

    那么 b 就是你的答案

Use intersection or intersection_update

  • intersection :

    a = [2,3,4,5,6,7,8,9,0]
    xyz = [0,12,4,6,242,7,9]
    ans = sorted(set(a).intersection(set(xyz)))
    
  • intersection_update:

    a = [2,3,4,5,6,7,8,9,0]
    xyz = [0,12,4,6,242,7,9]
    b = set(a)
    b.intersection_update(xyz)
    

    then b is your answer

梦回旧景 2024-12-05 23:27:17

嗯,只需一行即可完成。

a = [2,3,4,5,6,7,8,9,0]
xyz = [0,12,4,6,242,7,9]
print('\n'.join([str(x) for x in xyz if x not in a]))
-----------------------------------------------------------------------
12
242

This gives you:

Well, it's possible to do it in just one line.

a = [2,3,4,5,6,7,8,9,0]
xyz = [0,12,4,6,242,7,9]
print('\n'.join([str(x) for x in xyz if x not in a]))
-----------------------------------------------------------------------
12
242

This gives you:

寒江雪… 2024-12-05 23:27:17

虽然我真的很喜欢已接受的答案,但我想补充

for x in xyz:
    if x not in a:
        continue  # jump to the next element of xyz
    print(x)

一下讨论。

“优势”是有争议的,但正如这里已经指出的,并引用自 The Zen of Python,“简单胜于复杂”和“可读性很重要”。我声称 continue 的概念没有生成器表达式那么复杂。

Although I really like the accepted answer, I would like to add

for x in xyz:
    if x not in a:
        continue  # jump to the next element of xyz
    print(x)

to the discussion.

The "advantage" is debatable, but as already stated here and cited from the The Zen of Python, "simple is better than complex" and "readability counts". I claim that the concept of continue is less complex than generator expressions.

驱逐舰岛风号 2024-12-05 23:27:17

查找列表 a 和 b 的唯一公共元素的简单方法:

a = [1,2,3]
b = [3,6,2]
for both in set(a) & set(b):
    print(both)

A simple way to find unique common elements of lists a and b:

a = [1,2,3]
b = [3,6,2]
for both in set(a) & set(b):
    print(both)
咋地 2024-12-05 23:27:16

您可以使用 生成器表达式,如下所示:

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

for x in gen:
    print(x)

You can use generator expressions like this:

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

for x in gen:
    print(x)
好多鱼好多余 2024-12-05 23:27:16

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

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

获取 sorted 的 Pythonic 方式 两个 href="http://www.python.org/doc//current/library/stdtypes.html#set">set 是:

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

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

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

但是对于更复杂的循环,您可能希望通过迭代命名良好的 生成器表达式 和/或调用一个命名良好的函数。试图将所有内容都放在一行中很少是“Pythonic”。


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

我不确定您想用 enumerate,但如果 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

As per The Zen of Python (if you are wondering whether your code is "Pythonic", that's the place to go):

  • Beautiful is better than ugly.
  • Explicit is better than implicit.
  • Simple is better than complex.
  • Flat is better than nested.
  • Readability counts.

The Pythonic way of getting the sorted intersection of two sets is:

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

Or those elements that are xyz but not in a:

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

But for a more complicated loop you may want to flatten it by iterating over a well-named generator expression and/or calling out to a well-named function. Trying to fit everything on one line is rarely "Pythonic".


Update following additional comments on your question and the accepted answer

I'm not sure what you are trying to do with enumerate, but if a is a dictionary, you probably want to use the keys, like this:

>>> 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
つ低調成傷 2024-12-05 23:27:16

以下是已接受答案的简化/一行:

a = [2,3,4,5,6,7,8,9,0]
xyz = [0,12,4,6,242,7,9]

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

12
242

请注意,生成器保持内联。这是在 python2.7python3.6 上进行了测试(注意 print 中的括号;))

即使如此,老实说还是很麻烦: x 被提及次。

The following is a simplification/one liner from the accepted answer:

a = [2,3,4,5,6,7,8,9,0]
xyz = [0,12,4,6,242,7,9]

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

12
242

Notice that the generator was kept inline. This was tested on python2.7 and python3.6 (notice the parens in the print ;) )

It is honestly cumbersome even so: the x is mentioned four times.

花间憩 2024-12-05 23:27:16

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

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,您可以使用部分函数应用程序并使用运算符模块(提供大多数运算符的功能)。

https://docs.python.org/2/library/operator.html #模块运算符

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

I personally think this is the prettiest version:

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

Edit

if you are very keen on avoiding to use lambda you can use partial function application and use the operator module (that provides functions of most operators).

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)))
绿萝 2024-12-05 23:27:16

我可能会使用:

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

I would probably use:

for x in xyz: 
    if x not in a:
        print(x...)
情释 2024-12-05 23:27:16
a = [2,3,4,5,6,7,8,9,0]
xyz = [0,12,4,6,242,7,9]  
set(a) & set(xyz)  
set([0, 9, 4, 6, 7])
a = [2,3,4,5,6,7,8,9,0]
xyz = [0,12,4,6,242,7,9]  
set(a) & set(xyz)  
set([0, 9, 4, 6, 7])
孤独患者 2024-12-05 23:27:16

我喜欢 Alex 的回答,因为filter 正是应用于列表的 if,因此,如果您想在给定条件下探索列表的子集,这似乎是最有效的自然地,

mylist = [1,2,3,4,5]
another_list = [2,3,4]

wanted = lambda x:x in another_list

for x in filter(wanted, mylist):
    print(x)

此方法对于关注点分离很有用,如果条件函数发生变化,唯一需要修改的代码就是函数本身。

mylist = [1,2,3,4,5]

wanted = lambda x:(x**0.5) > 10**0.3

for x in filter(wanted, mylist):
    print(x)

当您不需要列表成员时,生成器方法似乎更好,但是对所述成员的修改,这似乎更适合生成器

mylist = [1,2,3,4,5]

wanted = lambda x:(x**0.5) > 10**0.3

generator = (x**0.5 for x in mylist if wanted(x))

for x in generator:
    print(x)

此外,过滤器与生成器一起工作,尽管在这种情况下效率不高

mylist = [1,2,3,4,5]

wanted = lambda x:(x**0.5) > 10**0.3

generator = (x**0.9 for x in mylist)

for x in filter(wanted, generator):
    print(x)

但是当然,这样写仍然很好这:

mylist = [1,2,3,4,5]

wanted = lambda x:(x**0.5) > 10**0.3

# for x in filter(wanted, mylist):
for x in mylist if wanted(x):
    print(x)

I liked Alex's answer, because a filter is exactly an if applied to a list, so if you want to explore a subset of a list given a condition, this seems to be the most natural way

mylist = [1,2,3,4,5]
another_list = [2,3,4]

wanted = lambda x:x in another_list

for x in filter(wanted, mylist):
    print(x)

this method is useful for the separation of concerns, if the condition function changes, the only code to fiddle with is the function itself

mylist = [1,2,3,4,5]

wanted = lambda x:(x**0.5) > 10**0.3

for x in filter(wanted, mylist):
    print(x)

The generator method seems better when you don't want members of the list, but a modification of said members, which seems more fit to a generator

mylist = [1,2,3,4,5]

wanted = lambda x:(x**0.5) > 10**0.3

generator = (x**0.5 for x in mylist if wanted(x))

for x in generator:
    print(x)

Also, filters work with generators, although in this case it isn't efficient

mylist = [1,2,3,4,5]

wanted = lambda x:(x**0.5) > 10**0.3

generator = (x**0.9 for x in mylist)

for x in filter(wanted, generator):
    print(x)

But of course, it would still be nice to write like this:

mylist = [1,2,3,4,5]

wanted = lambda x:(x**0.5) > 10**0.3

# for x in filter(wanted, mylist):
for x in mylist if wanted(x):
    print(x)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文