0

I have a long Python list like:

['A p=45 n=200 SNR=12', 'B p=2232 n=22 SNR=2']

I would like to get from this list a list of tuples containing the value of p, n and SNR.

So:

funz(['A p=45 n=200 SNR=12', 'B p=2232 n=22 SNR=2'])

would return:

[(45,200,12), (2232,22,2)]

The strings in the list have all the same structure.

2
  • 2
    How far along are you in writing the solution yourself? Where are you stuck? :) Commented Jul 8, 2014 at 23:28
  • [tuple(int(m) for m in re.findall(r'(\d+)', i)) for i in lst] Commented Jul 8, 2014 at 23:56

3 Answers 3

1
import re

data =  ['A p=45 n=200 SNR=12', 'B p=2232 n=22 SNR=2']

result = []

for x in data:
    result.append( map( int, re.search('p=(\d+).*n=(\d+).*SNR=(\d+)', x).groups()) )

print result

[[45, 200, 12], [2232, 22, 2]]
Sign up to request clarification or add additional context in comments.

Comments

1

Another option is this:

def funz(l):
    return [tuple(int(i.split('=')[1]) for i in item.split(' ')[1:]) for item in l]

Edited re @bvukelic's comment.

2 Comments

Damn, you beat me to it. Just do this, though: int(i.split('=')[1]) OP wants ints. And yeah, the left-most comprehension should be wrapped in tuple() for completeness.
@bvukelic they also aparently want tuples
0

You can use re.findall and a list comprehension:

>>> from re import findall
>>> lst = ['A p=45 n=200 SNR=12', 'B p=2232 n=22 SNR=2']
>>> def funz(lst):
...     return [tuple(map(int, findall("\d+", i))) for i in lst]
...
>>> funz(['A p=45 n=200 SNR=12', 'B p=2232 n=22 SNR=2'])
[(45, 200, 12), (2232, 22, 2)]
>>>

The Regex pattern \d+ matches one or more digits.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.