【问题标题】:Access and change data in a nested dict / list dataset Python 2.7+访问和更改嵌套字典/列表数据集中的数据 Python 2.7+
【发布时间】:2016-02-16 05:22:12
【问题描述】:

我需要一些有关访问和更改数据集中某些值的指导。我正在使用 Strava API,所以它的自行车数据。我有一个由字典组成的列表,其中包含一个字符串作为键,一个列表作为值:

[{'ride_name_one':[1.3,7.5,8.2,4.8]},{'ride_name_2:'[4.7,6.8,8.9,4.3]}]

我必须将这些值中的每一个从 m/s 转换为 km/h,并将其保存回该列表。我如何深入了解这些列表以更新它们?我猜是这样的:

streamsTest[0]['ride_name_one']

除了不确定如何使“ride_name_one”动态化?

有没有更好的地方进行这种转换?

到目前为止,这是我的代码:

athleteID = [xxxxxxxx]
activityIDs = [xxxxxxxxx,xxxxxxxxx]

def getSpeeds(cIDs,aIDs):

    print cIDs
    print aIDs

    streamsTest = []

    for i in aIDs:
        aID = i
        types = ['velocity_smooth']
        streams = client.get_activity_streams(aID, types=types, resolution='low')
        activity = client.get_activity(aID)

        if 'velocity_smooth' in streams.keys():
            actName = activity.name 
            raw = streams['velocity_smooth'].data
            streamsTest.append({actName:raw})   
        else: 
            print "velocity_smooth is not available"

    print streamsTest
    #[{'key':[1,2,3,4]},{'key:'[1,2,3,4]}]
    ### do m/s to km/h conversion on nested list data


getSpeeds(athleteID,activityIDs)

【问题讨论】:

    标签: python list python-2.7 dictionary nested


    【解决方案1】:

    想出了一个方法,如果有更好的方法,请随时发表评论。

    athleteID = [xxxxxxx]
    activityIDs = [xxxxxxxxx,xxxxxxxxx]
    
    def getSpeeds(cIDs,aIDs):
    
        streamsDicts = []
        streamsFinal = []
    
        for i in aIDs:
            aID = i
            types = ['velocity_smooth']
            streams = client.get_activity_streams(aID, types=types, resolution='low')
            activity = client.get_activity(aID) 
            if 'velocity_smooth' in streams.keys():
                actName = activity.name 
                raw = streams['velocity_smooth'].data
                streamsDicts.append({actName:raw[1:]})  
            else: 
                print "velocity_smooth is not available"
    
        for i in streamsDicts:
            for key, value in i.iteritems():
                value = [round((x * 3600) / 1000,2) for x in value]
                streamsFinal.append({key:value})
    
        print streamsFinal
    
    getSpeeds(athleteID,activityIDs)
    

    【讨论】:

      猜你喜欢
      • 2020-10-03
      • 2020-08-28
      • 2021-06-11
      • 1970-01-01
      • 2021-01-03
      • 1970-01-01
      • 2021-05-05
      • 2022-11-11
      • 2022-01-24
      相关资源
      最近更新 更多