【问题标题】:How to call a list when amount of indicators is not specified未指定指标数量时如何调用列表
【发布时间】:2015-05-18 17:33:40
【问题描述】:

当列表名称和指标不在同一个字符串中并且未指定指标数量时如何调用列表?除了 if 和 else 还有其他方法吗?它们不在同一个变量中,因为指标可能是可选的并且可能会发生变化。 示例(当指标数量只能为2时):

def Function(a, indicators):
    print a[indicators[0]][indicators[1]]

我只需要这段代码,但处理 8 个指标和 0 个指标没有错误。

提前感谢您的帮助。

编辑: 案例一:

a = [[[12, 7]], [["a"], ["b"]], [[4, "p", 3], ["17", "c"]]]
indicators = [2, 0, 1]

我希望函数打印 p。

案例 2:

a = "I AM UNIVERSAL!"
indicators = None

我想要打印 I AM UNIVERSAL 的函数!

如果我拼错了什么或做了什么误导性的事情,我很抱歉,但我是外国人,我的英语不太好。

【问题讨论】:

  • 我认为你需要添加一个更具体的例子,你的问题现在没什么意义。
  • @Trotom 你的问题缺少很多东西,指标和列表是什么样的?
  • 我不知道你在问什么。顺便说一句:不要使用 list 作为变量名。它会踩到list() 函数。
  • @Trotom 您是否要向call 一个名为list 的函数传递可变数量的参数/参数?
  • 欢迎来到 StackOverflow!你的意思是indeces而不是指标?听起来您在此处标记的 indicators 只是多维向量的索引,您不知道其维数。那是对的吗?更详细/提供更多代码将帮助我们帮助您。

标签: python list


【解决方案1】:

听起来您在问“我如何重构它以使其适用于任何大小的 indicators 列表?”

def Function(list, indicators):
    if len(indicators) == 1: return list[indicators[0]]
    if len(indicators) == 2: return list[indicators[0]][indicators[1]]
    if len(indicators) == 3: return list[indicators[0]][indicators[1]][indicators[2]]
    if len(indicators) == 4: return list[indicators[0]][indicators[1]][indicators[2]][indicators[3]]
    #etc forever

您可以使用for 循环迭代地应用索引。

def Function(list, indicators):
    x = list
    for index in indicators:
        x = x[index]
    return x

(附带的风格提示:考虑为list 取一个不同的名称,因为这已经是一个内置值的名称)

【讨论】:

  • 这可以作为一个表达式完成而不使用其他变量吗?接近这个:a = [12, 6, [7, "v"]]; i = [2, 1]; print a[i[j] for j in range(len(a[2]))]
  • 没有列表理解,你不能。 reduce(lambda x,y: x[y], indicators, a) 怎么样? (如果您使用 Python 3,则需要从 functools 导入 reduce
  • 它几乎可以完成这项工作,但是当我想更改此元素的值时,reduce() 返回给定元素的值。
猜你喜欢
  • 1970-01-01
  • 2020-12-27
  • 2017-11-16
  • 1970-01-01
  • 2016-01-03
  • 1970-01-01
  • 1970-01-01
  • 2015-05-31
  • 1970-01-01
相关资源
最近更新 更多