检查字典中的浮点值以了解Python中的条件
我有一本如图所示的字典,我想知道我应该如何编写代码来检查每个键的每个值,并检查它们是否满足某个条件,如值大于8等等 这些值是浮点值,并且每个字典值区域有多个值检查字典中的浮点值以了解Python中的条件,python,dictionary,Python,Dictionary,我有一本如图所示的字典,我想知道我应该如何编写代码来检查每个键的每个值,并检查它们是否满足某个条件,如值大于8等等 这些值是浮点值,并且每个字典值区域有多个值 def main(): #defining main function magList = [] #magnitude list of all together regionList = [] #creating list to hold region names wholeList = [] combi
def main(): #defining main function
magList = [] #magnitude list of all together
regionList = [] #creating list to hold region names
wholeList = []
combinedList = []
with open("earthquakes.txt", "r") as eqList: #opens earthquake text file and gets the magnitudes
eqList.readline()
for line in eqList:
line = line.split()
magList.append(float(line[1])) #appends magnitude as float values in list
with open("earthquakes.txt", "r") as eqList2: #open file 2nd time for gathering the region name only
eqList2.readline()
for line in eqList2:
line = line.split()
line = line[0:7] + [" ".join(line[7:])] #takes whole line info and adds to list
wholeList.append(line)
greatMag = [] #creating lists for different category magnitudes
majorMag = []
strongMag = []
moderateMag = []
for x in magList: #conditions for seperating magnitude
if x >= 8:
greatMag.append(x)
elif 7 <= x <= 7.9:
majorMag.append(x)
elif 6 <= x <= 6.9:
strongMag.append(x)
elif 5 <= x <= 5.9:
moderateMag.append(x)
for line in wholeList: #takes only magnitude and region name from whole list
combinedList.append([line[7], line[1]])
infoDict = {} #creates dictionary
for key, val in combinedList: #makes one key per region and adds all values corresponding to the region
infoDict.setdefault(key, []).append(val)
print(infoDict)
for k, v in infoDict.items():
for i in v:
if i >= 8:
print("Great Magnitude:", i)
pass
if __name__ == "__main__": #runs main function
main()
def main():#定义主函数
magList=[]#所有项目的震级列表
regionList=[]#创建列表以保存区域名称
完整列表=[]
组合列表=[]
用open(“sequences.txt”,“r”)作为eqList:#打开地震文本文件并获取震级
eqList.readline()
对于eqList中的行:
line=line.split()
magList.append(float(第[1]行))#将幅值作为浮点值附加到列表中
打开(“sequences.txt”、“r”)作为eqList2:#第二次打开文件仅用于收集区域名称
eqList2.readline()
对于eqList2中的行:
line=line.split()
line=line[0:7]+[“”。join(line[7:])]#获取整行信息并添加到列表中
wholeList.append(行)
greatMag=[]#创建不同类别大小的列表
majorMag=[]
strongMag=[]
中庸标记=[]
对于磁表中的x:#分离震级的条件
如果x>=8:
greatMag.append(x)
如果你能从你的字典中挑选一些样本并在这里发布,那会很有帮助。可能是重复的吗。如果不是,那肯定是相关的。它使用字典理解基于关键字过滤字典。另外,您想对符合条件的数据做什么?添加了我的代码,您无法运行它,因为您没有文本文件,只是想看看我在结尾处是如何完成的。值是字符串列表。如果i>=8,行“if i>=8”会给我一个错误,如果i>=8:TypeError:unorderable types:str()>=int()我遇到了同样的问题,你来这里之前做过类似的事情。它不应该给我一个字符串比较错误,因为值是浮点数而不是字符串,但无论如何它都是。@Lompang,仔细看看你的数据-你的浮点数实际上是字符串,试试if float(i)>something:
Ah我忘了你可以在做条件时将其更改为浮点数,这很有意义,谢谢!
for k,v in d.items(): # iterate through key, value of dict 'd'
for i in v: # iterate to dict value which is a list
if i > 8: # your condition
# do something here
pass