开发者社区> 问答> 正文

将._replace的命名元组字段名称作为函数的参数传递

所以我有一个命名元组,说:

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

展开
收起
is大龙 2020-03-23 16:49:33 462 0
1 条回答
写回答
取消 提交回答
  • 创建一个匿名dict并将其解压缩:

    symbol_copy[row] = symbol[row]._replace(\*{field_to_update: prev_values[row]})
    

    通过field_to_update = prev_values [row]传递的普通关键字参数是静态的;它将左侧作为固定字符串而不是变量传递(甚至不允许使用引号)。但是dict字面语法需要引用字符串键,因此按预期将field_to_update视为变量。

    回答来源:stackoverflow

    2020-03-23 16:49:37
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载