我有一个使用for循环生成的列表。它返回:
home1-0002_UUID 3457077784 2132011944 1307504896 62%
home1-0003_UUID 3457077784 2088064860 1351451980 61%
home1-0001_UUID 3457077784 2092270236 1347246604 61%
如何只返回第三列和第五列?
EDIT 当我收到错误时,它会说'Nonetype'对象不可迭代
for index, elem in enumerate(my_list):
print (index,elem)
我也尝试使用list(enumerate(my_list))获取索引,但它没有工作我得到TypeError:' 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 :(得分: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)