【问题标题】:How do I check if a parameter given to a function is a list?如何检查给函数的参数是否是列表?
【发布时间】:2016-11-23 10:08:51
【问题描述】:

如果给定的参数不是列表,我希望函数返回注释。如果是列表,我想进行一些操作。

下面是代码:

def manipulate_data(*num):
  if type(num) is not list:
    return "Only lists allowed"
  else:
    positive = 0
    for n in num:
        if n >= 0:
            positive = positive + 1

【问题讨论】:

  • 你的问题是什么
  • num 的类型始终为tuple。删除*,代码将起作用。
  • if not isinstance(num, list):
  • @ettanany positive 已经在 for 之外,无需将其移到 if 范围之外
  • 在 python 中使用 isinstance()。

标签: python function conditional


【解决方案1】:

通过使用 *nums 参数,您可以将所有参数打包到一个列表中。 official documentation 可能有用。

manipulate_data(1, 2, 3, 4, 5) 将导致num = (1, 2, 3, 4, 5)manipulate_data([1, 2, 3, 4, 5]) 将导致num = ([1, 2, 3, 4, 5],) 这是一个只有一个元素的元组。删除 * 或者如果需要处理多个列表作为参数,则使用循环来检查每个元组元素。

def manipulate_data(num):
  if type(num) is not list:
    return "Only lists allowed"
  else:
    positive = 0
    for n in num:
        if n >= 0:
            positive += 1
    return positive
def manipulate_multiple(*nums):
  for num in nums:
    manipulate_data(num)

记住这个函数还没有返回任何东西

【讨论】:

  • 您的回答为我指明了正确的方向,但是,我想做的是使用提供的列表执行操作。例如,如果提供的列表是 [1, 3, 2, 3],我希望能够返回列表中元素的总和,示例应该返回 9。代码返回 1
  • @Weirdsourcer 该函数没有像我提到的那样返回所有内容,编辑它以返回正数,因为它正在计算它们。要添加所有元素,请尝试sum(num)
【解决方案2】:

好的,让它更干净,除了a,b,所有左边的位置参数都将传递给c

>>> def func(a, b, *c):
...     print a
...     print b
...     print c

...

>>> func(1, 2, 3, 4, 5)

1
2
(3, 4, 5)

【讨论】:

  • 答案没有解释用户为什么会发生这种情况或在哪里可以找到有关此的文档。至少应该为谷歌搜索提供一些关键字
猜你喜欢
  • 2017-11-07
  • 1970-01-01
  • 2013-06-05
  • 2016-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-07
  • 1970-01-01
相关资源
最近更新 更多