我想知道是否有一条快捷方式可以在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) 我有两个列表,第一个列表保证只包含一个列表而不是第二个列表.我想知道创建一个新列表的最Pythonic方法,其中偶数索引值来自第一个列表,其奇数索引值来自第二个列表.
# example inputs
list1 = ['f', 'o', 'o']
list2 = ['hello', 'world']
# desired output
['f', 'hello', 'o', 'world', 'o']
Run Code Online (Sandbox Code Playgroud)
这有效,但并不漂亮:
list3 = []
while True:
try:
list3.append(list1.pop(0))
list3.append(list2.pop(0))
except IndexError:
break
Run Code Online (Sandbox Code Playgroud)
如何实现这一目标呢?什么是最Pythonic方法?
我想写一个复活列表的函数,[1,5,3,6,...]
并[1,1,5,5,3,3,6,6,...]
想知道如何做到这一点?谢谢
执行以下操作的pythonic方法是什么:
我有两个列表a和b相同的长度n,我想形成列表
c = [a[0], b[0], a[1], b[1], ..., a[n-1], b[n-1]]
Run Code Online (Sandbox Code Playgroud)