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)
CodePudding user response:
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]
}
CodePudding user response:
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']
CodePudding user response:
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.
CodePudding user response:
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']