所以我有一个命名元组,说:
from collections import namedtuple
Symbol = namedtuple('Symbol', 'name code industry date_au open high low close volume weekday_au date_utc_unixtimestamp prev_volume', defaults = ('DEFAULT', 'DEF', 'DEFAULT', '01/01/1970', 0.0, 0.0, 0.0, 0.0, 0, 'Mon', 0, 0))
我做一些测试数据:
ont_data = [
Symbol(name = '1300 SMILES LIMITED', code ='ONT', industry = 'Tech', date_au = '03/05/2020', open = 10.0, high = 12.0, low = 9.5, close = 11.0, volume = 1000, weekday_au = 'Sun', date_utc_unixtimestamp = 123),
Symbol(name = '1300 SMILES LIMITED', code ='ONT', industry = 'Tech', date_au = '15/05/2020', open = 12.0, high = 12.0, low = 5.5, close = 9.0, volume = 999, weekday_au = 'Fri', date_utc_unixtimestamp = 125),
Symbol(name = '1300 SMILES LIMITED', code ='ONT', industry = 'Tech', date_au = '17/01/2020', open = 4.0, high = 90.0, low = 54.5, close = 74.0, volume = 27, weekday_au = 'Wed', date_utc_unixtimestamp = 5)
]
现在,我想创建此命名元组的副本,并对特定属性动态进行一些替换:
def set_prev_val(symbol, prev_values, field_to_update):
"""
Iterate over a copy of Symbol named tuple and replace some attribute values.
Return a copy of Symbol named tuple with replaced previous values of some field_to_update
args:
@symbol - A descending sorted named tuple representing stock symbol data
@prev_values - A list of previous values (from a descending sorted Symbol)
@field_to_update - A field in a Symbol named tuple to update
"""
symbol_copy = symbol
for row in range(0, len(symbol_copy)):
symbol_copy[row] = symbol[row]._replace(field_to_update = prev_values[row])
return symbol_copy
当我用prev_values_data = [1,2,3]
测试时,我得到:
ValueError: Got unexpected field names: ['field_to_update']
我想要的是prev_volume
字段,要使用prev_values_data
的值进行更新
我认为不是传递field_to_update
的字符串值,而是将命名元组中属性的实际名称作为参数名称!
有没有一种方法可以将某些“名称”属性作为参数从函数传递给命名元组中的..replace调用?(假设在命名的元组属性名称中存在“名称”)
Python 3.7
问题来源:stackoverflow
创建一个匿名dict
并将其解压缩:
symbol_copy[row] = symbol[row]._replace(\*{field_to_update: prev_values[row]})
通过field_to_update = prev_values [row]
传递的普通关键字参数是静态的;它将左侧作为固定字符串而不是变量传递(甚至不允许使用引号)。但是dict字面语法需要引用字符串键,因此按预期将field_to_update视为变量。
回答来源:stackoverflow
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。