Python 在不展平的情况下子集字符串列表

Python 在不展平的情况下子集字符串列表,python,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 E

我有以下清单:

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]

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

您非常接近。尝试:

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

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

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

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

由于您希望结果是一个列表列表,因此应尝试使用
[[item for item in sublist if(condition)]形式的命令,用于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 ])

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

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

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

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