不理解python中的列表理解 [英] Not comprehending list comprehension in python

查看:68
本文介绍了不理解python中的列表理解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在做一些列表理解练习时,我不小心做了下面的代码.这最终为列表中的所有 16 个条目打印了 True/False.

threes_and_fives =[x % 3 == 0 or x % 5 == 0 for x in range(16)]打印threes_and_fives

在我使用它之后,我能够得到我想要的结果,它打印了列表中可以被 3 或 5 整除的数字.

threes_and_fives =[x for x in range(16) if x % 3 == 0 or x % 5 == 0]打印threes_and_fives

我的问题是为什么第一个代码评估为真或假而另一个没有?我正在尝试了解 python,所以解释越多越好:) 谢谢!

解决方案

您可能缺少的是 Python 中的关系运算符没有什么特别之处,它们是表达式,就像其他任何表达式一样,碰巧产生布尔值.举一些例子:

<预><代码>>>>1 + 1 == 2真的>>>2 + 2 == 5错误的>>>[1 + 1 == 2, 2 + 2 == 5][真假]

列表推导式简单地将涉及可迭代序列元素的表达式收集到列表中:

<预><代码>>>>[x for x in xrange(5)] # 数字 0 到 4[0, 1, 2, 3, 4]>>>[x**2 for x in xrange(5)] # 0 到 4 的平方[0, 1, 4, 9, 16]

你的第一个表达式就像那样工作,但表达式产生布尔值:它告诉 Python 组装一个布尔值列表,对应于匹配的序数是否可以被 3 或 5 整除.

您真正想要的是一个数字列表,按指定条件过滤.Python 列表推导式通过可选的 if 子句支持这一点,该子句采用表达式并将结果列表限制为布尔表达式为其返回真值的那些项.这就是您的第二个表达式正常工作的原因.

While doing some list comprehension exercises, i accidentally did the code below. This ended up printing True/False for all 16 entries on the list.

threes_and_fives =[x % 3 == 0 or x % 5 == 0 for x in range(16)]
print threes_and_fives

After i played with it i was able to get the outcome that I wanted, where it printed the numbers from that list that are divisible by 3 or 5.

threes_and_fives =[x for x in range(16) if x % 3 == 0 or x % 5 == 0]
print threes_and_fives

My questions is why did the first code evaluated to true or false and the other one didn't? I'm trying to get a grasp of python so the more explanations the better :) Thanks!

解决方案

What you may be missing is that there is nothing special about relational operators in Python, they are expressions like any others, ones that happen to produce Boolean values. To take some examples:

>>> 1 + 1 == 2
True
>>> 2 + 2 == 5
False
>>> [1 + 1 == 2, 2 + 2 == 5]
[True, False]

A list comprehension simply collects expressions involving elements of an iterable sequence into a list:

>>> [x for x in xrange(5)]      # numbers 0 through 4
[0, 1, 2, 3, 4]
>>> [x**2 for x in xrange(5)]   # squares of 0 through 4
[0, 1, 4, 9, 16]

Your first expression worked just like that, but with the expression producing Booleans: it told Python to assemble a list of Boolean values corresponding to whether the matching ordinal is divisible by 3 or 5.

What you actually wanted was a list of numbers, filtered by the specified condition. Python list comprehensions support this via an optional if clause, which takes an expression and restricts the resulting list to those items for which the Boolean expression returns a true value. That is why your second expression works correctly.

这篇关于不理解python中的列表理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆