How can i adjust my code to read every other line?
1 2 3 | with open(data_path) as f: content = f.readlines() content = [x.strip() for x in content] |
下面的代码将读取每一行并将其插入到列表中。但是我想要的代码应该读第一行,跳过第二行,然后读第三行,或者简单地用
在你的列表理解中,简单地将步骤设置为2。
1 | content = [x.strip() for x in content[::2]] |
正如你所说,你的问题是:
should read the first line and skip the second then read the third
您可以在一行中完成所有操作:
One line solution:
1 | print([item.strip() for index,item in enumerate(open('file.txt','r')) if index % 2 == 0]) |
above list comprehension is same as:
1 2 3 4 | final_list=[] for index,item in enumerate(open('file.txt','r')): if index % 2 == 0: final_list.append(item.strip()) |