How to split a compound word split by hyphen into two individual words

痞子三分冷 提交于 2021-02-08 13:07:02

问题


I have the following list

list1= ['Dodd-Frank', 'insurance', 'regulation']

I used the following to remove the hyphen

new1 =[j.replace('-', ' ') for j in list1]

The result I got

new1= ['Dodd Frank', 'insurance', 'regulation']

The result that Ideally want is

new1= ['Dodd', 'Frank', 'insurance', 'regulation']

How can I accomplish this in the most pythonic (efficient way)


回答1:


list1 = ['Dodd-Frank', 'insurance', 'regulation']
new1 = '-'.join(list1).split('-')
print(new1)

Prints:

['Dodd', 'Frank', 'insurance', 'regulation']



回答2:


list2 = []
[list2.extend(i.split("-")) for i in list1] 

list2:

['Dodd', 'Frank', 'insurance', 'regulation']



回答3:


This can be done with a single list comprehension, without needing you to construct any intermediate data structures:

my_list = ['Dodd-Frank', 'insurance', 'regulation']

def split_hyphens(lst):
    return [i for word in lst for i in word.split("-")]

print(split_hyphens(my_list))

with output

['Dodd', 'Frank', 'insurance', 'regulation']



回答4:


From Ugly to Beautiful

Beautiful is better than ugly.

But it's usually rewarding to move from ugly code to beautiful code. So, we'll first attack this problem using loops, and then we'll massage the loop-y solution into a one-liner in a number of steps.

A First Attempt

res = []
for item in list1:
    sublist = item.split("-")
    for subitem in sublist:
        res.append(subitem)

A Second Attempt

We can do better by splitting sublist in the header of the inner for loop, in order to avoid the assignment just before the loop.

res = []
for item in list1:
    for subitem in item.split("-"):
        res.append(subitem)

And for the Final Act...

Now that we have our loop in iterate-then-append form, we can conveniently massage it into a one-liner.

res = [subitem for item in list1 for subitem in item.split("-")]


来源:https://stackoverflow.com/questions/59119824/how-to-split-a-compound-word-split-by-hyphen-into-two-individual-words

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!