mustang_39211 mustang_39211 - 3 months ago 8
Python Question

python: how to return 2 columns/index in a list

I have a list that I generated using a for loop. it returns:

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


How can I return only the third and fifth columns?

EDIT
when I get an error it says 'Nonetype' object is not iterable

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


I also tried to get the index by using list(enumerate(my_list)) but it doesn't work I get TypeError: 'NoneType' object is not iterable

this is how I populate the list:

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)

Answer

As far as I cannot post a comment I will do my best to give you a solution to the question.

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]
    third_column_list = []
    fifth_column_list = []
    # Separate by line break and filter any empty string
    filtered_use_list = filter(empty_string_filter, use.split('\n')[: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.
        third_column_list.append(split_line[2])
        fifth_column_list.append(split_line[4])

    return third_column_list, fifth_column_list

So the idea is split every single line by white spaces and filter any empty string left in order to get the 3rd and 5th column (index 2 and 4 respectively)

Note that i'm returning a two lists: one with the content of the 3rd column and another for the 5th column