2016-09-01 65 views
-1

我有一個列表,我使用for循環生成。返回:python:如何返回列2列/索引

home1-0002_UUID 3457077784 2132011944 1307504896 62% 
home1-0003_UUID 3457077784 2088064860 1351451980 61% 
home1-0001_UUID 3457077784 2092270236 1347246604 61% 

我怎麼能只返回第三和第五列?

編輯 當我得到它說「Nonetype」對象不是可迭代

for index, elem in enumerate(my_list): 
    print (index,elem) 

我也試圖通過使用列表(枚舉(my_list))來獲得指數,但它不工作,我的錯誤獲得類型錯誤:「NoneType」對象不是可迭代

我這是怎麼填充列表:

def h1ost(): 
    p1 = subprocess.Popen("/opt/lustre-gem_s/default/bin/lfs df /lustre/home1 | sort -r -nk5",stdout=subprocess.PIPE, shell=True) 
    use = p1.communicate()[0] 
    for o in use.split('\n')[:6]: 
     if "Available" not in o and "summary" not in o: 
      print (o) 
+0

如何列表分離的任何空字符串?你能添加實際的輸出嗎?這是一個列表還是數據框? – depperm

+0

'[[col [2],col [4]] col in the_list]'? – Claudiu

+0

它是一個數組的數組? – depperm

回答

1

據我不能發表評論,我會盡我最大的努力給ÿ對問題的解決方案。

def empty_string_filter(value): 
    return value != '' 

def h1ost(): 
    p1 = subprocess.Popen("/opt/lustre-gem_s/default/bin/lfs df /lustre/home1 | sort -r -nk5",stdout=subprocess.PIPE, shell=True) 
    use = p1.communicate()[0] 
    new_file_content_list = [] 
    # Separate by line break and filter any empty string 
    filtered_use_list = filter(empty_string_filter, use.split(os.linesep)[:6]) 
    for line in filtered_use_list : 
     # Split the line and filter the empty strings in order to keep only 
     # columns with information 
     split_line = filter(empty_string_filter, line.split(' ')) 
     # Beware! This will only work if each line has 5 or more data columns 
     # I guess the correct option is to check if it has at least 5 columns 
     # and if it hasn't do not store the information or raise an exception. 
     # It's up to you. 

     new_file_content_list.append('{0} {1}'.format(split_line[2] , split_line[4])) 

    return os.linesep.join(new_file_content_list) 

這樣的想法是分裂用空格每一行和過濾離開,以獲得第3和第5列(索引2和4分別)

+0

謝謝你的迴應。這工作得很好。結果是h1ost() (['62%','61%','61%','60%','59%'],['/ luster/home1 [OST:2]','/光澤/ home1 [OST:3]','/ luster/home1 [OST:1]','/ luster/home1 [OST:0]','/ luster/home1 [OST:4]']) 可以被格式化回原始狀態,還是通過將它寫入文件而獲得成功? –

+0

我已經修改了答案,以便檢索準備寫入文件的單個字符串。通常情況下,加入會在一個外部函數中完成,以便數據管理 – Almasyx

+0

這個工作很好!當我打印退貨時,退貨中的\ n完美無缺。 –