2

Suppose I have a list of strings that look like:

strings_list = ["a=2,b=3,c=14","a=1,b=4,c=0","a=1,b=80,c=3"]

and I want to iterate over these strings and read off the values of the 'b' parameter. How do I do this? Could you help me filling in the line I wrote as a comment

b_array = []
For s in strings_list:
   # [read off b parameter as a number, call it b_value]
   b_array.append(b_value)

4 Answers 4

3

You could just split each string on , and then again on =, saving the values if the first part of the split is b (or some other name):

name = 'b'
result = [int(v[1]) for v in [a.split('=') for s in strings_list for a in s.split(',')] if v[0] == name]

Output (for your sample data):

[3, 4, 80]

You could also take a regex-based approach as shown by @Thefourthbird, and use a defaultdict to extract all values of all parameters at once:

import re
from collections import defaultdict

p = defaultdict(list)
[p[k].append(int(v)) for (k, v) in re.findall('(\w+)=(\d+)', ','.join(strings_list))]

Output (for your sample data):

{
 'a': [2, 1, 1],
 'b': [3, 4, 80],
 'c': [14, 0, 3]
}
Sign up to request clarification or add additional context in comments.

4 Comments

Sweet, that's it.
@Thefourthbird You can do a similar thing with your code, b_array = [int(v) for v in re.findall(r"\bb=(\d+)", ','.join(strings_list))] - on my testing it was almost 3x faster
The joining of a comma on the collection is faster than appending to the array you mean right? Because you are joining the list to a string using this ','.join(strings_list) That's a handy one, I did not know :-) Due to the versatility of your answer I expected yours to be accepted. You already have my 1+
@Thefourthbird most of the improvement is from the joining of the strings, but there's a small (~5%) improvement through not calling extend as well.
1

You can capture the digits in a group where the key equals b and use re.findall to get all group matches.

strings_list = ["a=2,b=3,c=14", "a=1,b=4,c=0", "a=1,b=80,c=3"]
b_array = []

[b_array.extend(re.findall(r"\bb=(\d+)", s)) for s in strings_list]

print(b_array)

Output

['3', '4', '80']

2 Comments

I failed to do it as a one liner, but I think would have made sense to present results as a dict: {'a':[2,1,1], 'b':[...], 'c'.:[...]}.
@JeJe see my edited answer, it can be done with a defaultdict...
1

One possible solution you could do is iterating through the strings_list and for each element, splitting that into a list by commas. Then you would just take the second element, subtract the b=, and convert the remaining number to an integer. The code would look like this:

strings_list = ["a=2,b=3,c=14","a=1,b=4,c=0","a=1,b=80,c=3"]
b_array = []
for s in strings_list:
   splitted = s.split(",")
   b_array.append(int(splitted[1][2:]))
print(b_array) # Returns [3, 4, 80]

If you don't want the b_array to be filled with integers and instead with strings of the b value, simply take out the part where it is converted to an integer.

1 Comment

This is very tailor made to the exact example list that he gave, it will fail if he wants to find any other parameter than "b" or if at some point in the actual list the "b" parameter is not the second parameter, or if anything else happens to differ from the example given. I consider this a very bad solution.
0

Use regular expression

import re

strings_list = ["a=2,b=3,c=14","a=1,b=4,c=0","a=1,b=80,c=3"]

b_array = []
for s in strings_list:
    for match in re.finditer(r'([^=,]+)=([^,]+)', s):
        name, value = match.groups()
        if name == 'b':
            b_array.append(value)

print(b_array)
# ['3', '4', '80']

or a more generic approach, in case you want other parameters than "b":

from collections import defaultdict
import re

strings_list = ["a=2,b=3,c=14","a=1,b=4,c=0","a=1,b=80,c=3"]

parameters = defaultdict(list)

for s in strings_list:
    for match in re.finditer(r'([^=,])+=([^,])', s):
        name, value = match.groups()
        parameters[name] += [value]


print(parameters['b'])
# ['3', '4', '8']

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.