python - 对中间有数据的字符串列表进行排序

标签 python sorting

所以我有一个与 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)。我们将此函数用作 sortkey 参数,以将此值用作排序键。您的日期格式可以像字符串一样排序。您可能可以使用更复杂的 extract_line 函数来仅提取日期。

关于python - 对中间有数据的字符串列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40026332/

相关文章:

python - 防止 Pandas 将 None 读作 Nan

python - 覆盖 Python Tkinter 中的默认选项卡行为

python - 多处理的queue.get()什么时候返回DONE?

python - 带有空标记的 Matplotlib 绘图线

python - numpy 矩阵,通过对每一行进行排序将 0 设置为值

android - 如何在android顶部的 ListView 中添加新项目

c - 如何对数字进行降序排序

c - 使用 C 中的条件按字典顺序对 3 个字符串进行排序

java - 如何使用比较器定义自定义排序顺序?

iphone - 在 UITableViewController 中对行进行排序