子集化字符串列表的列表而无需展平

时间:2019-02-22 19:12:52

标签: python

我有以下列表:

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]

我该怎么做?

3 个答案:

答案 0 :(得分:8)

您非常接近。试试:

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

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

答案 1 :(得分:1)

由于您希望结果为列表列表,因此应尝试使用[[item for item in sublist if (condition)] for sublist in biglist]形式的命令。试试这个:

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']]

print([ [info for info in student if "Race Ethnicity" in info] for student in A ])

答案 2 :(得分:1)

您还可以在listcomp中使用函数filter()

[list(filter(lambda x: x.startswith('Race'), i)) for i in A]