且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

不理解python中的列表理解

更新时间:2022-10-17 19:25:28

您可能缺少的是 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.