python - 将子列表的最后一个元素附加到列表中
问题描述
我有一个列表列表,我需要在其中获取最后一个元素并将其附加到一个新列表中。我的第一个函数的输出的小例子:上下文:“数据”是空字典我也添加了列表列表顺便说一句
['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 中创建直方图。
解决方案
您可以跳过第一个国家/地区名称[1:]
(如果格式确实是一致的)
ric_scale = []
for sublist in data[1:]:
ric_scale.append(sublist[-1])
推荐阅读
- c++ - 在 C++ Ubuntu 中安装 FTP 客户端(库)
- elasticsearch - 弹性搜索问题“iphone”没有显示正确的结果
- cassandra - 在 Mac 上启动 Cassandra
- angular - 访问 vega 数据集的外部 url
- python-import - __name__ 和 __package__ 的区别和用途
- node.js - CSRF 令牌在我的反应应用程序中不起作用
- c++ - 我的解决方案比给定的示例解决方案慢多少?
- c# - 在 Asp.Net Core MVC 视图中找不到类型或命名空间
- python - python中的密码保护或加密sqlite db文件
- python - 如何根据列值和不同的日期时间索引计算熊猫数据框中的差异?