我有以下清单:
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]
我该怎么做?你知道吗
也可以在listcomp中使用函数
filter()
:你很接近。尝试:
嵌套列表理解将保持您的二维性。你知道吗
因为您希望结果是一个列表列表,所以应该尝试
[[item for item in sublist if (condition)] for sublist in biglist]
形式的命令。试试这个:相关问题 更多 >
编程相关推荐