简体   繁体   中英

How do I excecute a command for every split?

I am new to python, and am trying to filter a string that looks similar to this:

"{Red,Plant,Eel}{Blue,Animal,Maple}{Yellow,Plant,Crab}"

And so on for 100s of three word sets.

I want to extract the second word from every set marked by "{ }", so in this example I want the output:

"Plant,Animal,Plant"

And so on.

How can I do it efficiently?

As of Right now I am using string.split(",")[1] individually for each "{ }" group.

Thanks.

This does the trick:

str_ = "{Red,Plant,Eel}{Blue,Animal,Maple}{Yellow,Plant,Crab}"
res = [x.split(',')[1] for x in str_[1:-1].split('}{')]

and produces

['Plant', 'Animal', 'Plant']

with the str_[1:-1] we remove the initial "{" and trailing "}" and we then split the remaining entities on every instance of "}{" thus producing:

["Red,Plant,Eel", "Blue,Animal,Maple", ...]

finally, for every string, we split on "," to obtain

[["Red", "Plant", "Eel"], ...]

from which we keep only the first element of each sublist with x[1] .

Note that for your specific purpose, slicing the original string with str_[1:-1] is not mandatory (works without it as well), but if you wanted only the first instead of the second item it would make a difference. The same holds in case you wanted the 3rd.


If you want to concatenate the strings of the output to match your desired result, you can simply pass the resulting list to .join as follows:

out = ','.join(res)

which then gives you

"Plant,Animal,Plant"

尝试这个:

[i.split(',')[1] for i in str_[1:].split('}')[:len(str_.split('}'))-1]]

another solution is using regex, a bit more complicated, but it's a technique worth talking about:

import re
input_string = "{Red,Plant,Eel}{Blue,Animal,Maple}{Yellow,Plant,Crab}"
regex_string = "\{\w+\,(\w+)\,\w+\}"

result_list = re.findall(regex, input_string)

then result_list output is:

['Plant', 'Animal', 'Plant']

here's a link for regex in python and an online regex editor

#!/bin/python3

string = "{Red,Plant,Eel}{Blue,Animal,Maple}{Yellow,Plant,Crab}"
a = string.replace('{','').replace('}',',').split(',')[1::3]
print(a)

result is ['Plant', 'Animal', 'Plant']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM