I have the following question to ask. I have a list of bs4.element.Tags like [[tag1, tag2, tag3], [tag4, tag5], [tag6], [tag7, tag8, tag9, tag10]]. So each sub list contains names of actors from different movies. So the first sub-list has three actors, the second two actors and so on.
What I do is to remove the bs4.element.Tag by calling the function .text per element of each sub-list. Then I append the result to a new list which is like: [str1, str2, str3, str4, str5, str6, str7, str8, str9, str10]. Although this is not my desirable result. I want the actors in the new list to be grouped as in the original list.
So the desirable result should be: [[str1, str2, str3], [str4, str5], [str6], [str7, str8, str9, str10]] Where str = string name of each actor.
Do you know how can I achieve this?
My example (follow the pictures):
It's tough to do completely without seeing your code, but you're going to want to iterate through your element tags, pull out the content from each element into a list, then append that into a final list. So something like:
final_list = []
for tag in tags_list:
actors = tag.find_all('a')
actors_list = [ x.text.strip() for x in actors ]
final_list.append(actors_list)
You can do list comprehension as suggested by @Ezer K. But I personally prefer the map function.
actor_list = []
for tags in tag_list:
actor_list.append(list(map(lambda x: x.text, tags)))
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.