2017-02-14 106 views
0

請參閱下面的確切代碼。基本上,我試圖從csv文件中獲取信息,並創建一個包含所有用戶名(不含空格或重複項)的列之一的列表。我能夠獲得所有用戶名的列表,但我找不到刪除空白的方法。我已經嘗試過濾器以及其他方法,但似乎無法做到正確。我的代碼是:刪除列表中的空嵌套列表

with open('test.csv') as f: 
reader = csv.DictReader(f) 
initialExport = [] 
for row in reader: 
    iE = [row['Computer Name'], row['Username']] 
    initialExport.append(iE) 

for i in initialExport: 
    i.pop(0) 
finalExport = filter(None, initialExport) 
print(finalExport) 
+0

你想刪除空白的用戶名或空白? –

+0

你能發表一個好的和不好的輸入例子嗎? – TemporalWolf

回答

1

而不是過濾出來,爲什麼不乾脆避免在第一時間加入空白項:

for row in reader: 
    if row['Username']: 
     iE = [row['Computer Name'], row['Username']] 
     initialExport.append(iE) 
1

initialExport是(單)列出了一個清單,當您試圖篩選他們。其中一些列表可能包含空字符串。這不會讓他們成爲空單!所以無論如何,他們的真實性都是真實的。你可以通過篩選出來:

finalExport = [l for l in initialExport if l[0]] 

但爲什麼在首位添加Computer Name列,如果你只是彈出它?爲什麼做一個嵌套列表,如果你是在一個元素只是感興趣:

finalExport = [row['Username'] for row in reader if row['Username']] 
+0

對不起,我應該解釋 - 我將使用'計算機名稱',但在本例中不使用。 「計算機名稱」字段仍然相關,但我只是簡單地測試一種方法,僅顯示用戶名(不帶空格)。 – Neemaximo

0

這顯示了一種方法來去除空列表,只包含從LST空列表空的元組和列表。下面的代碼將不會刪除:

  • 空巢元組(一個或多個級別)
  • 空巢名單有兩個以上的水平

賦予LST的最後兩個條目。

import collections 

lst = [1, 2, "3", "three", [], [1, 2, "3"], [[], []], 4, 
     [[1], []], [[], [], []], 5, "6", (1,2), 7,(), 
     ((),()), [[[]]]] 

for index, item in enumerate(lst): 
    # if it is an empty list [] or tuple() 
    if not item: 
     del lst[index] 
    # if it is a list containing only empty sublists [[], [], ...] 
    elif isinstance(item, collections.MutableSequence): 
     if not [i for sublist in item for i in sublist]: 
      del lst[index] 

print(lst) 

輸出:

[1, 2, '3', 'three', [1, 2, '3'], 4, [[1], []], 5, '6', (1, 2), 7, ((),()), [[[]]]] 

四個元件從LST除去在上面的例子中,即[],[[],[]],[[],[],[]]和()。

0

purge(list, [elements to purge])將遞歸清除從列表中的element所有副本的任何子列表,包括通過除去更深元件([[[], []]]將被完全去除)創建的任何元件。因爲我們正在修改就地列表中,我們有我們當前深度每次​​重新啓動我們刪除一個元素:

def purge(lst, bad): 
    restart = True 
    while restart: 
     restart = False 
     for index, ele in enumerate(lst[:]): 
      if ele in bad: 
       del lst[index] 
       restart = True 
       break 
      elif isinstance(ele, list): 
       purge(ele, bad) 
       if lst[index] in bad: 
        del lst[index] 
        restart = True 
        break 

例子:

>>> lst = [[[[], [[],[]]]]] 
>>> purge(lst, [[]]) 
[] 

>>> lst = [1, 2, "3", "three", [], [1, 2, "3"], [[], []], 4, 
     [[1], []], [[], [], []], 5, "6", (1,2), 7, [[[]]]] 
>>> purge(lst, [[]]) 
[1, 2, '3', 'three', [1, 2, '3'], 4, [[1]], 5, '6', (1, 2), 7] 
>>> purge(lst, ['3']) 
[1, 2, 'three', [1, 2], 4, [[1]], 5, '6', (1, 2), 7]