You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何获取排序后列表首尾行的首个元素

获取排序后国家列表的首尾国家名称

场景1:数据已在Python列表中

如果你的数据已经处理成Python列表(不管是拆分后的字段列表还是原始字符串行),直接用列表索引就能快速获取首尾元素的第一个字段:

情况A:数据是拆分后的字段列表

# 已按人口降序排好的列表,每个元素是拆分后的字段集合
countries_data = [
    ["Bahrain", "1701575", "0.0368", "60403", "760", "Asia"],
    ["Timor-Leste", "1318445", "0.0196", "25326", "14870", "Asia"],
    ["Cyprus", "1207359", "0.0073", "-8784", "9240", "Asia"],
    ["Bhutan", "771608", "0.0112", "8516", "38117", "Asia"],
    ["Macao", "649335", "0.0139", "8890", "30781", "Asia"],
    ["Maldives", "540544", "0.0181", "9591", "300", "Asia"]
]

# 取首行第一个元素(人口最多的国家)
most_populous = countries_data[0][0]
# 取末行第一个元素(人口最少的国家)
least_populous = countries_data[-1][0]

print(f"人口最多:{most_populous}")
print(f"人口最少:{least_populous}")

情况B:数据是原始字符串行的列表

# 已按人口降序排好的原始字符串行列表
country_lines = [
    "Bahrain,1701575,0.0368,60403,760,Asia",
    "Timor-Leste,1318445,0.0196,25326,14870,Asia",
    "Cyprus,1207359,0.0073,-8784,9240,Asia",
    "Bhutan,771608,0.0112,8516,38117,Asia",
    "Macao,649335,0.0139,8890,30781,Asia",
    "Maldives,540544,0.0181,9591,300,Asia"
]

# 拆分首行字符串,取第一个字段
most_populous = country_lines[0].split(",")[0]
# 拆分末行字符串,取第一个字段
least_populous = country_lines[-1].split(",")[0]

print(f"人口最多:{most_populous}")
print(f"人口最少:{least_populous}")

场景2:从文件读取已排序的数据

如果数据存在本地文本文件(比如countries.csv)且已经按人口降序排好,直接读取文件内容后处理:

with open("countries.csv", "r", encoding="utf-8") as f:
    # 读取所有非空行,自动去掉换行符
    lines = [line.strip() for line in f if line.strip()]

most_populous = lines[0].split(",")[0]
least_populous = lines[-1].split(",")[0]

print(f"人口最多:{most_populous}")
print(f"人口最少:{least_populous}")

关键要点

  • Python列表用[0]取第一个元素,[-1]取最后一个元素,这是最直接的索引用法
  • split(",")会把字符串按逗号拆分成列表,取索引[0]就能得到国家名称
  • 因为数据已经按人口降序排好,不需要额外排序,直接取首尾行即可

内容的提问来源于stack exchange,提问作者Ruby W.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 14:42:55