Skip to main content
 首页 » 编程设计

python之在不展平的情况下对字符串列表的列表进行子集化

2025年05月04日13artech

我有以下列表:

A = [['Computer Science', 'Gender- Male', 'Race Ethnicity- Hispanic', 'Race Ethnicity- White'], 
    ['Computer Science', 'Gender- Female', 'Race Ethnicity- White'], 
    ['History', 'Gender-Female', 'Race Ethnicity- Black'], 
    ['Mechanical Engineering', 'Geder- Male', 'Race Ethnicity- American Indian or Alaskan Native', 'Race Ethnicity- Hispanic']] 

我只想保留涉及种族和民族的元素。这就是我想要的结果:

B = [['Race Ethnicity- Hispanic', 'Race Ethnicity- White'], 
    ['Race Ethnicity- White'], 
    ['Race Ethnicity- Black'], 
    ['Race Ethnicity- American Indian or Alaskan Native', 'Race Ethnicity- Hispanic']] 

下面的排序工作但不保留列表结构列表

[y for x in test for y in x if "Race Ethnicity" in y] 

我该怎么做?

请您参考如下方法:

你很接近。尝试:

[[y for y in x if 'Race' in y] for x in test] 

嵌套列表理解将保持您的二维性。