在python列表中删除无

Q1。
在这里输入图像说明

我想要得到的输出为:

[Randy, Shaw] 

输出看起来像

 ['Randy', 'None', 'None', 'Shaw', 'None', 'None'] 

但它并没有消除“无”的价值。
这是我的代码

 from openpyxl import load_workbook workbook = load_workbook('C:/Users/Desktop/test.xlsx') print(workbook.get_sheet_names()) sheet=workbook.get_sheet_by_name('marks') iterheaders = iter(sheet[1]) headers = [str(cell.value) for cell in iterheaders if cell is not None and cell != ''] Keyword_list = list(filter(None, headers)) 

我什至尝试了以下,但它也没有工作:

 Keyword_list = [i for i in headers if (None) != len(i)] 

Q2。 在相同的代码中,如果我想通过它的索引而不是它的名字在openpyxl中获取表格。 我怎么做?

你可以像这样过滤:

 s = ['Randy', 'None', 'None', 'Shaw', 'None', 'None'] s = [i for i in s if i != "None"] 

请记住,在你的列表中你有string"None" ,而不是None

对于Q2:

 workbook = load_workbook('C:/Users/Desktop/test.xlsx') sheet = wworkbook.worksheets[0] #here, either loop over or access by whatever index you want. 

您的none值不是文字Nonetypes值。 他们的弦乐。 因此,你需要对string进行testing。 例如:

 >>> lst = ['Randy', 'None', 'None', 'Shaw', 'None', 'None'] >>> [el for el in lst if el != 'None'] ['Randy', 'Shaw'] >>>