Joh*_*ohn 0 python list-comprehension list
我想做这样的事情:
Input: [3, 4, 1, 2]
Output: ["3", "", "", "4", "", "", "1", "", "", "2", "", ""]
Run Code Online (Sandbox Code Playgroud)
我知道
x = [3, 4, 1, 2]
[str(i) for i in x]
Run Code Online (Sandbox Code Playgroud)
将产生没有额外空字符串的列表.我的问题是,是否有一种简单的方法可以让Python继续为理解中的每个输入项创建3个输出项.如果没有,我当然可以写一个循环......
list-comprehension中的double for循环就像map+ chain你可以使用的:
[j for i in x for j in [str(i), "", ""]]
# ['3', '', '', '4', '', '', '1', '', '', '2', '', '']
Run Code Online (Sandbox Code Playgroud)
使用map和chain语法,您可以:
from itertools import chain
list(chain.from_iterable([str(i), "", ""] for i in x))
# ['3', '', '', '4', '', '', '1', '', '', '2', '', '']
Run Code Online (Sandbox Code Playgroud)