简体   繁体   English

列表理解中的Python语法错误?

[英]Python syntax error in list comprehension?

Professor introduced a new way to write some code. 教授介绍了一种编写一些代码的新方法。

x=[1,2,3,4,5,6,7,8,9]
y=[i<6 , for i in x]
print(y)

I am expecting the following output 我期望以下输出

True, True, True, True, True, False, False, False, False

Is there a syntax error in the y statement? y语句中是否存在语法错误? My program is highlight the for part. 我的程序是突出显示的。

You don't use , in a list comprehension. 你不使用,在列表理解。 This works fine: 这工作正常:

x = [1, 2, 3, 4, 5, 6, 7, 8, 9]

y = [i<6 for i in x]

print(y)

Returns [True, True, True, True, True, False, False, False, False] 返回[True, True, True, True, True, False, False, False, False]

What your professor is teaching you is list comprehension . 教授教你的是清单理解 I love them. 我爱他们。 Succinct to write. 写得简洁。

Alternatively, you could have written it like this, which is way longer: 另外,您也可以这样写,这样会更长:

z = []

for i in x:
    if i < 6:
        z.append(True)
    else:
        z.append(False)

print(z)

Would return [True, True, True, True, True, False, False, False, False] 将返回[True, True, True, True, True, False, False, False, False]

By the way, the above code can also be written with shorthand if else syntax: 顺便说一下,如果使用其他语法,上面的代码可以用简写形式编写:

    z = []
    for i in x:
        z.append(True) if i < 6 else z.append(False)
    return z

Anyway, here is a more full solution with unit testing for your perusal. 无论如何,这是一个更完整的解决方案,带有单元测试供您细读。

import unittest

def so_26923986(x):

    y = [i < 6 for i in x]
    return y 

def so_26923986_1(x):

    z = []
    for i in x:
        z.append(True) if i < 6 else z.append(False)
    return z

Unit Test 单元测试

# Unit Test
class Test(unittest.TestCase):
    def testcase(self):
        self.assertEqual(so_26923986([1, 2, 3, 4, 5, 6, 7, 8, 9]), [True, True, True, True, True, False, False, False, False])
        self.assertEqual(so_26923986_1([1, 2, 3, 4, 5, 6, 7, 8, 9]), [True, True, True, True, True, False, False, False, False])

        self.assertEqual(so_26923986([1, 2, 3]), [True, True, True])
        self.assertEqual(so_26923986_1([1, 2, 3]), [True, True, True])

        self.assertEqual(so_26923986([1, 2, 7, 10, 3, 8]), [True, True, False, False, True, False])
        self.assertEqual(so_26923986_1([1, 2, 7, 10, 3, 8]), [True, True, False, False, True, False])

unittest.main()

Test Passing 测试通过

Ran 1 test in 0.000s

OK

You should write like : 您应该这样写:

    x=[1,2,3,4,5,6,7,8,9]
    y=[i<6 for i in x]
    print y

Your code is fine but remove , from list. 您的代码是好的,但删除,从列表中。

output : 输出:

   [True, True, True, True, True, False, False, False, False]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM