繁体   English   中英

带有列表的Python列表理解

[英]Python List Comprehension for a list with lists

我正在文件中进行字符串替换,并使用csv writer在输出中写入选项卡。 使用csv编写器意味着我需要一个格式正确的列表来提供给csv编写器以进行输出。 我输入指定选项卡和换行符的输入行,并将其放入csv编写器知道如何写出的列表中。

我下面的代码实际上完成了所需的任务,我想知道的是,是否可以使用for循环上的列表理解功能进一步完善代码,以将选项卡分为自己的列表并替换列表中的现有项。 这是代码:

testInput = "\\t//blah/...\\t//blah_blah/...\\n\\t-//blah/...\\t//blah/...\\n\\t//blah/...\\t//blah_blah/...\\n\\t//blah/...\\t//blah/...\\n"

new_lines = [z for z in testInput.split('\\n') if z]

x=-1
if testInput.find("\\t") >= 0:
    for line in new_lines:
        x+=1
        lines = line.split("\\t")
        new_lines[x] = lines
replacement_value = new_lines

使用以下代码,for for循环将转换new_lines:

watchWindow

对此:

NewWatchWindow

可以使用列表理解重写for循环吗?

我认为您可以在列表组件内使用列表组件来做到这一点...

[[s for s in z.split("\\t")] for z in testInput.split('\\n') if z]

由于我很好奇,看来您可以以这种方式回去...

"\\n".join(["\\t".join([a for a in x]) for x in new_lines])+"\\n"

暂无
暂无

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

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