首页 > 解决方案 > 将子列表的最后一个元素附加到列表中

问题描述

我有一个列表列表,我需要在其中获取最后一个元素并将其附加到一个新列表中。我的第一个函数的输出的小例子:上下文:“数据”是空字典我也添加了列表列表顺便说一句

['PANAMA', ['2006/10/18', '5.0'], ['2006/10/14', '4.8']]
['MISSOURI', ['2006/10/18', '3.4']]
['INDONESIA', ['2006/10/18', '4.9'], ['2006/10/18', '4.9']]

这些列表来自一个包含地震数据的文件,下面是我的项目代码:

import matplotlib.pyplot as plt
from itertools import islice
from operator import itemgetter


def get_list(data, key):
    r_list = [key]
    for i in data:
        if i == key:
            for j in data[key]:
                r_list.append(j)
            break
# Return the list.
   return r_list


def main():
    f = open("earthquakes.txt")
    data = {}
    for line in f.readlines():
        list1 = line.split()
        dat_mag = [list1[1], list1[0]]
    if list1[len(list1) - 1] in data:
        data[list1[len(list1) - 1]].append(dat_mag)
    else:
        data[list1[len(list1) - 1]] = [dat_mag]
    for key in data:
        print(get_list(data, key))

    ric_scale = list(map(itemgetter(-1), islice(data, 1, None)))
    print(ric_scale)

    plt.hist(ric_scale, bins=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

    plt.xlabel('Magnitudes')
    plt.ylabel('Occurrences')
    plt.title('Earthquake Intensity')

    plt.show()


main()

我需要得到最终值:“5.0”、“4.8”等。这只是文件的一个小样本。我该怎么做呢,到目前为止,我的代码是使用该国的最后一个字母。我需要它来列出日期和震级编号。

  ric_scale = []
  for sublist in data:
      ric_scale.append(sublist[-1])

我的预期输出是:

[5.0, 4.8, 3.4, 4.9, 4.9]

我计划使用幅度在 MPL 中创建直方图。

标签: python

解决方案


您可以跳过第一个国家/地区名称[1:](如果格式确实是一致的)

ric_scale = []
  for sublist in data[1:]:
      ric_scale.append(sublist[-1])

推荐阅读