在不展平的情况下对字符串列表进行子集设置

2024-05-12 22:59:10 发布

您现在位置: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]

我该怎么做?你知道吗


Tags: oringendermalefemalecomputerscienceindian
3条回答

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

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

你很接近。尝试:

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

嵌套列表理解将保持您的二维性。你知道吗

因为您希望结果是一个列表列表,所以应该尝试[[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 ])

相关问题 更多 >