删除 python 列表中的 None
Delete None in python list
Q1.
我希望输出为:
[Randy, Shaw]
输出看起来像
['Randy', 'None', 'None', 'Shaw', 'None', '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 中的名称来获取 sheet 怎么办。我该怎么做?
您可以这样过滤:
s = ['Randy', 'None', 'None', 'Shaw', 'None', 'None']
s = [i for i in s if i != "None"]
请记住,在您的列表中有字符串 "None"
,而不是对象 None
第 2 季度:
workbook = load_workbook('C:/Users/Desktop/test.xlsx')
sheet = wworkbook.worksheets[0] #here, either loop over or access by whatever index you want.
您的 none 值不是文字 None
类型值。他们的弦。因此,您需要针对字符串测试它们。例如:
>>> lst = ['Randy', 'None', 'None', 'Shaw', 'None', 'None']
>>> [el for el in lst if el != 'None']
['Randy', 'Shaw']
>>>
Q1.
我希望输出为:
[Randy, Shaw]
输出看起来像
['Randy', 'None', 'None', 'Shaw', 'None', '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 中的名称来获取 sheet 怎么办。我该怎么做?
您可以这样过滤:
s = ['Randy', 'None', 'None', 'Shaw', 'None', 'None']
s = [i for i in s if i != "None"]
请记住,在您的列表中有字符串 "None"
,而不是对象 None
第 2 季度:
workbook = load_workbook('C:/Users/Desktop/test.xlsx')
sheet = wworkbook.worksheets[0] #here, either loop over or access by whatever index you want.
您的 none 值不是文字 None
类型值。他们的弦。因此,您需要针对字符串测试它们。例如:
>>> lst = ['Randy', 'None', 'None', 'Shaw', 'None', 'None']
>>> [el for el in lst if el != 'None']
['Randy', 'Shaw']
>>>