我想知道是否有一条快捷方式可以在Python列表中列出一个简单的列表.
我可以在for循环中做到这一点,但也许有一些很酷的"单行"?我用reduce尝试了,但是我收到了一个错误.
码
l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
reduce(lambda x, y: x.extend(y), l)
Run Code Online (Sandbox Code Playgroud)
错误信息
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <lambda>
AttributeError: 'NoneType' object has no attribute 'extend'
Run Code Online (Sandbox Code Playgroud) 是否可以使用列表理解来模拟sum()之类的东西?
例如 - 我需要计算列表中所有元素的乘积:
list = [1, 2, 3]
product = [magic_here for i in list]
#product is expected to be 6
Run Code Online (Sandbox Code Playgroud)
执行相同的代码:
def product_of(input):
result = 1
for i in input:
result *= i
return result
Run Code Online (Sandbox Code Playgroud)