所以我有一个与 kibana 索引相关的字符串列表,字符串如下所示:
λ curl '10.10.43.210:9200/_cat/indices?v'
health status index pri rep docs.count docs.deleted store.size pri.store.size
yellow open filebeat-2016.10.08 5 1 899 0 913.8kb 913.8kb
yellow open filebeat-2016.10.12 5 1 902 0 763.9kb 763.9kb
yellow open filebeat-2016.10.13 5 1 816 0 588.9kb 588.9kb
yellow open filebeat-2016.10.10 5 1 926 0 684.1kb 684.1kb
yellow open filebeat-2016.10.11 5 1 876 0 615.2kb 615.2kb
yellow open filebeat-2016.10.09 5 1 745 0 610.7kb 610.7kb
返回的日期未排序。我想按索引(即日期)对它们进行排序 filebeat-2016-10.xx ASC 或 DESC 都可以。
就目前情况而言,我像这样隔离字符串:
subp = subprocess.Popen(['curl','-XGET' ,'-H', '"Content-Type: application/json"', '10.10.43.210:9200/_cat/indices?v'], stdout=subproce$
curlstdout, curlstderr = subp.communicate()
op = str(curlstdout)
kibanaIndices = op.splitlines()
for index,elem in enumerate(kibanaIndices):
if "kibana" not in kibanaIndices[index]:
print kibanaIndices[index]+"\n"
kibanaIndexList.append(kibanaIndices[index])
但无法以有意义的方式对它们进行排序。
最佳答案
这是你需要的吗?
lines = """yellow open filebeat-2016.10.08 5 1 899 0 913.8kb 913.8kb
yellow open filebeat-2016.10.12 5 1 902 0 763.9kb 763.9kb
yellow open filebeat-2016.10.13 5 1 816 0 588.9kb 588.9kb
yellow open filebeat-2016.10.10 5 1 926 0 684.1kb 684.1kb
yellow open filebeat-2016.10.11 5 1 876 0 615.2kb 615.2kb
yellow open filebeat-2016.10.09 5 1 745 0 610.7kb 610.7kb
""".splitlines()
def extract_date(line):
return line.split()[2]
lines.sort(key=extract_date)
print("\n".join(lines))
这里 extract_date
是一个返回第三列的函数(如 filebeat-2016.10.12
)。我们将此函数用作 sort
的 key
参数,以将此值用作排序键。您的日期格式可以像字符串一样排序。您可能可以使用更复杂的 extract_line
函数来仅提取日期。
关于python - 对中间有数据的字符串列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40026332/