python取特定行,如何在python中的2条特定行之间读取

I'm having a variable which holds the contents that is somewhat similar to this

**** SOME JUNK DATA ****

**** SOME JUNK DATA ****

**** SOME JUNK DATA ****

Main_data1;a;b;c;dss;e;1

Main_data2;aa;bb;sdc;d;e;2

Main_data3;aaa;bbb;ccce;d;e;3

Main_data4;aaaa;bbbb;cc;d;e;4

Main_data5;aaaaa;bbbbb;cccc;d;e;5

**** SOME JUNK DATA ****

**** SOME JUNK DATA ****

**** SOME JUNK DATA ****

I want to read data that starts with Main_data1.{ Read only the last column and store it into a list} . Please note that this is a variable that holds this data and this is not a file.

My Desired Output:

Some_list=[1,2,3,4,5]

I thought of using something like this.

for line in var_a.splitlines():

if Main_data1 in line:

print (line)

But there are more than 200 lines from which I need to read the last column. What could be an efficient way of doing this

解决方案

You can use a list comprehension to store the numbers :

my_list = [int(line.strip().split(';')[-1]) for line in my_var.split('\n') if line.startswith('Main_data5')]

Also note that as a more pyhtonic way you better to use str.startswith() method rather than in operator. (with regards to this poing that it might happen to one line has Main_data5 in the middle of the line!)

If you have two case for start of the line you can use an or operator with two startswith consition.

my_list = [int(line.strip().split(';')[-1]) for line in my_var.split('\n') if line.startswith('Main_data5') or line.startswith('Main_data1')]

But if you have more key-words you can use regex.For example if you want to match all the linse that stats with Main_data and followed by a number you can use re.match():

import re

my_list = [int(line.strip().split(';')[-1]) for line in my_var.split('\n') if re.match(r'Main_data\d.*',line)]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值