sharath
sharath

Reputation: 55

Extract list elements based on

I have a list which looks like this:

['48638 0 Q qp32', '48708 0 Q qp32', '48736 0 Q batch', '48737 0 Q batch', '48738 588:30:5 R qp32', '48758 45:00:40 R qp32', '48763 274:19:4 R qp256', '48772 0 Q qp32', '48782 02:25:16 R qp256', '48783 0 Q qp256', '48786 0 Q qp256', '48802 05:57:29 R qp64'] 

How can I extract numbers like 48638 based on parameters like Q or R and put the output into a separate list? Since this is inside an entire list I am not able to figure out any solution.

Output must be in two separate lists:

Upvotes: 0

Views: 55

Answers (3)

Shang
Shang

Reputation: 75

data=['48638 0 Q qp32', '48708 0 Q qp32', '48736 0 Q batch', '48737 0 Q batch', '48738 588:30:5 R qp32', '48758 45:00:40 R qp32', '48763 274:19:4 R qp256', '48772 0 Q qp32', '48782 02:25:16 R qp256', '48783 0 Q qp256', '48786 0 Q qp256', '48802 05:57:29 R qp64'] 
qs=[int(s.split(' ')[0]) for s in data if 'Q' in s]
rs=[int(s.split(' ')[0]) for s in data if 'R' in s]

Upvotes: 0

ferhatelmas
ferhatelmas

Reputation: 3978

def get_numbers(your_list, typ):
    res = []
    for e in your_list:
        ls = e.split()
        if ls[2] == typ:
            res.append(int(ls[0]))
    return res

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1121914

You can use in membership tests to see if the character is present, then use string splitting to extract the first element:

parameter = 'R' # or 'Q'
[s.partition(' ')[0] for s in yourlist if parameter in s]

This produces strings (so ['48638', '48708', '48736', '48783', '48786'] for'Q'). If you needed *integers*, simply addint()`:

[int(s.partition(' ')[0]) for s in yourlist if parameter in s]

Demo:

>>> yourlist = ['48638 0 Q qp32', '48708 0 Q qp32', '48736 0 Q batch', '48737 0 Q batch', '48738 588:30:5 R qp32', '48758 45:00:40 R qp32', '48763 274:19:4 R qp256', '48772 0 Q qp32', '48782 02:25:16 R qp256', '48783 0 Q qp256', '48786 0 Q qp256', '48802 05:57:29 R qp64'] 
>>> parameter = 'R'
>>> [s.partition(' ')[0] for s in yourlist if parameter in s]
['48738', '48758', '48763', '48782', '48802']
>>> [int(s.partition(' ')[0]) for s in yourlist if parameter in s]
[48738, 48758, 48763, 48782, 48802]

Upvotes: 2

Related Questions