pythonjsonlistpyqgis

How to print a specific row from a list in python


I have a list called 'DistInt' that contains values of Intensity with corresponding Distances for an earthquake event. Is there a way I can just print a specific row within list?

import math
import json

# Open JSON file
f = open("Path_to.geojson")

# Returns JSON object as a dictionary
data = json.load(f)

for feature in data['features']:
    ml = float(feature['properties']['magnitude'])
    h = float(feature['properties']['depth'])
    i = 0

# Formula for working out Distances for MMI
    Io = 1.5 * (ml - 1.7 * 0.4343 * math.log(h) + 1.4)

    for i in range(1, 13, 1):
        Iso = float(i)
        a = (Io - Iso) / (1.8 * 0.4343)
        d = math.exp(a)
        d = d - 1
        if d <= 0:
            d = 0
        else:
            d = math.sqrt(h * h * d)
            DistInt = [Iso, d]
            print(DistInt)

Would print the DistInt list:

[1.0, 609.1896122140013]
[2.0, 321.0121765154287]
[3.0, 168.69332169329735]
[4.0, 87.7587868508665]
[5.0, 43.88709626561051]
[6.0, 17.859906969392682]

I would like to just print, for example, the row - [2.0, 321.0121765154287]


Solution

  • I guess what you want to do is something like this:

    DistIntArray = []
    
    for i in range(1, 13, 1):
    Iso = float(i)
    a = (Io - Iso) / (1.8 * 0.4343)
    d = math.exp(a)
    d = d - 1
    if d <= 0:
        d = 0
    else:
        d = math.sqrt(h * h * d)
        DistInt = [Iso, d]
        print(DistInt)
    DistIntArray.append(DistInt)
        
    print("the first element of array: ", DistIntArray[0])
    print("the second element of array: ", DistIntArray[1])
    
    for i in range(0,len(DistIntArray)):
        print("An element of DistIntArray",DistIntArray[i])
    
    
    for aDistInt in DistIntArray:
        print("Getting an element of DistIntArray",aDistInt)
    

    I just created an array and added the calculated DistInt tuple in each iteration of the first for loop. This way I can get any element of the calculated DistInt variables.

    Here, DistIntArray is an array of array because the variable DistInt is a tuple which is an array. The for loops are just different ways of iterating over arrays.

    Besides this, I think your code seems to be buggy since the DistInt = [Iso, d] is indented with the else block. It means it will do the assignment only in the else block. I guess this line and the print line should be written like this:

    if d <= 0:
        d = 0
    else:
        d = math.sqrt(h * h * d)
    DistInt = [Iso, d]
    print(DistInt)
    DistIntArray.append(DistInt)