简体   繁体   English

每次按不同对数将列表中的元素分组在一起

[英]Grouping the elements of a list together by different number of pairs each time

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]]. 我有一个bs4.element.Tag列表,例如[[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. 我要做的是通过在每个子列表的每个元素上调用函数.text来删除bs4.element.Tag。 Then I append the result to a new list which is like: [str1, str2, str3, str4, str5, str6, str7, str8, str9, str10]. 然后,将结果附加到一个新列表中,例如:[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. 因此理想的结果应该是:[[str1,str2,str3],[str4,str5],[str6],[str7,str8,str9,str10]]其中str =每个参与者的字符串名称。

Do you know how can I achieve this? 你知道我怎么能做到吗?

My example (follow the pictures): 我的例子 (如下图):

list of bs4.element.tags bs4.element.tags的列表

list of actor names 演员名单

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. 完全看不到代码很难做到,但是您将要遍历element标签,将每个元素的内容提取到列表中,然后将其附加到最终列表中。 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. 您可以按照@Ezer K的建议进行列表理解。但是我个人更喜欢map函数。

actor_list = []
for tags in tag_list:
    actor_list.append(list(map(lambda x: x.text, tags))) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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