[英]How to access the key values in a nested python dictionary with variables?
我正在使用此QA中的方法清理一些ROS機器人代碼。 這與ROS無關。
這是原始代碼:
data = []
data.append(sensor[thermo].data.thermo)
data.append(sensor[imu].data.imu.x)
data.append(sensor[imu].data.imu.rotation.x)
現在,我有一個包含所有主題的元組列表,因此我可以循環瀏覽:
topics = [('thermo', 'thermo'),
('imu', 'imu.x')
('imu', 'imu.rotation.x')]
和:
for sensor, topic in topics:
data.append(getattr[sensor].data, topic)
這適用於thermo
,但不適用於imu
,並且出現以下錯誤:
AttributeError:“ imu”對象沒有屬性“ x”
如何修復getattr
語句以實現此處的目標?
可以使用functools
的功能reduce
:
reduce(getattr, "att1.att2.att3".split('.'), sensor[imu])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.