2017-07-07 62 views
2

Q1。
enter image description here在python列表中刪除無

我想輸出:

[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中獲取表單,該怎麼辦?我怎麼做?

+3

,因爲這是*字符串*'「無」'不是單例,NoneType對象'None' –

+2

的可能的複製(https://開頭stackoverflow.com/questions/1157106/remove-all-occurrences-of-a-value-from-a-list) – yabk

回答

2

您可以過濾像這樣:

s = ['Randy', 'None', 'None', 'Shaw', 'None', 'None'] 

s = [i for i in s if i != "None"] 

請記住,在你的列表中,您有串"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. 
+0

嗨,那工作。謝謝!但Q2呢?有沒有辦法? – Analyst

+0

@程序員請參閱我最近的編輯。 – Ajax1234

1

你無值不是文字None類型值。他們的絃樂。因此,你需要對字符串進行測試。例如:?從列表中刪除某個值的所有出現]

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