【问题标题】:Python: Named placeholders How to organize data in a string array?Python:命名占位符如何组织字符串数组中的数据?
【发布时间】:2020-05-14 01:41:02
【问题描述】:

我正在使用 Firebase 数据库。我正在阅读一个孩子并收到这些数据:

输入:

Connection = db.child(UniqueID).child("Devices").get()
Data =Connection.val()
print(Data)
print(Data[0])
print(Data[1])

输出:

[None,{'DeviceAddress': '1', 'DeviceType': 'Heat', 'Status': 'Heat Alarm'},
{'DeviceAddress': '2', 'DeviceType': 'Smoke', 'Status': 'Smoke Alarm'},
{'DeviceAddress': '3', 'DeviceType': 'Button', 'Status': 'Button Alarm'}]

None

{'DeviceAddress': '1', 'DeviceType': 'Heat', 'Status': 'Heat Alarm'}

我怎样才能像这样对数据进行排序:

sortedData=Data[1] "这里有一些代码"

sortedData[0] -> 包含“1”

sortedData[1] -> 包含“热量”

sortedData[DeviceAddress] -> 包含'1'

sortedData[DeviceType] -> 包含“Heat”

【问题讨论】:

    标签: arrays python-3.x string firebase


    【解决方案1】:

    如果您使用 pandas 库中的 DataFrame,您将能够按索引分类访问数据。

    from pandas import DataFrame
    
    Data = [None,{'DeviceAddress': '1', 'DeviceType': 'Heat', 'Status': 'Heat Alarm'},
    {'DeviceAddress': '2', 'DeviceType': 'Smoke', 'Status': 'Smoke Alarm'},
    {'DeviceAddress': '3', 'DeviceType': 'Button', 'Status': 'Button Alarm'}]
    
    data_frame = DataFrame(Data[1:])
    
    sortedData = data_frame.iloc[0]   # this gets first row of data
    
    print(sortedData.iloc[0])         # get the value by index
    print(sortedData.DeviceType)      # get the value by category
    

    【讨论】:

    • 谢谢,这正是我想要的。
    【解决方案2】:

    您可以在循环中访问字典值以获取每个列表。

    Data = [None,{'DeviceAddress': '1', 'DeviceType': 'Heat', 'Status': 'Heat Alarm'},
    {'DeviceAddress': '2', 'DeviceType': 'Smoke', 'Status': 'Smoke Alarm'},
    {'DeviceAddress': '3', 'DeviceType': 'Button', 'Status': 'Button Alarm'}]
    
    tempdata = Data[1:]
    for e in tempdata:
      vals = list(e.values())
      print(vals)
    

    输出

    ['1', 'Heat', 'Heat Alarm']
    ['2', 'Smoke', 'Smoke Alarm']
    ['3', 'Button', 'Button Alarm']
    

    【讨论】:

    • 感谢您的回答。如果我读 vals[0],我能得到 '1' 吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-05
    • 2017-12-20
    • 2021-04-07
    • 1970-01-01
    • 2023-03-02
    • 1970-01-01
    相关资源
    最近更新 更多