Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
153 views
in Technique[技术] by (71.8m points)

python - How to go from list comprehension to loop in this case?

I have to perform the following action without using list comprehensions. I have a list that looks like the following one:

["Mi Fa Sol", 'Mi', "Mi Fa Sol La Si", "Do Si", " Mi Si Fa", "Fa"]

What I want to obtain is a list like the following one:

["Mi", "Fa", "Sol", "Mi", "Mi", "Fa", "Sol", "La", "Si", "Do", "Si", "Mi", "Si", "Fa", "Fa"]

I can do that in the following way, I think:

    lst = [elem.strip().split() for elem in lst]
    lst = [elem for sub_lst in lst for elem in sub_lst]

But I have no idea how to accomplish the same result without list comprehensions.

question from:https://stackoverflow.com/questions/65885619/how-to-go-from-list-comprehension-to-loop-in-this-case

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your current version using two separate list comprehensions can be simplified to use a single list comprehension instead:

lst = [e for elem in lst for e in elem.split()]

But, if you want to use a traditional for loop instead, then you can loop through each elem of lst as you currently do, and use list.extend() to add the splitted elements to a result list res:

lst = ["Mi Fa Sol", 'Mi', "Mi Fa Sol La Si", "Do Si", " Mi Si Fa", "Fa"]
res = []
for elem in lst:
    res.extend(elem.split())
print(res)

Output:

['Mi', 'Fa', 'Sol', 'Mi', 'Mi', 'Fa', 'Sol', 'La', 'Si', 'Do', 'Si', 'Mi', 'Si', 'Fa', 'Fa']

You can assign res back to lst if needed afterwards.

Side note: since you use the default delimiter for split(), you can also omit the redundant strip() in this case.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...