【问题标题】:python function that iterates over list or, in case of int, just takes int [duplicate]迭代列表的python函数,或者在int的情况下,只需要int [重复]
【发布时间】:2018-03-18 00:45:04
【问题描述】:

有没有更优雅的方式?我想让 python 遍历 arg,如果它是一个列表,或者只取 arg,如果它是一个 int。数据是一个 numpy.ndarray

def plot(data, run, t):
    if isinstance(run, int):
        run = [run]

    fig = plt.figure()
    ax = fig.add_subplot(111)

    for run in run:
        plt.plot(t, data[run])


    plt.savefig('data.png', dpi=200)

【问题讨论】:

  • 取决于您在函数中使用arg 做什么。你只想打印?
  • 我想用它作为索引来访问数组的元素
  • @Baedsch 你能再显示几行代码来说明这一点吗?
  • 当您最初创建run 时,为什么不总是将其设为一个列表(包含1 个或多个元素)?不混合不同的数据类型似乎更自然,并且不再需要这种奇怪的修复
  • 是的,已经实现了,既然是框架,有它就好了

标签: python


【解决方案1】:

您可以减少代码中的一行:

def fcn(arg):
    for a in ([arg] if isinstance(arg, int) else arg):
        print a

【讨论】:

  • 看起来好多了,谢谢
【解决方案2】:
def example(*arg):
  print "I was called with", len(arg), "arguments:", arg

>>> example(1)
I was called with 1 arguments: (1,)
>>> example(1, 2,3)
I was called with 3 arguments: (1, 2, 3)

【讨论】:

  • 我DVed。在第二种情况下,您没有传递列表,因此这不能解决 OP 的问题。
猜你喜欢
  • 2015-05-11
  • 1970-01-01
  • 2016-12-08
  • 2019-02-22
  • 2017-09-16
  • 2011-11-13
  • 2023-03-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多