首页 > 解决方案 > 如何使用输入数组参数定义函数

问题描述

我想用一个输入数组参数创建一个函数,然后从第 1、4 和 6 个元素返回一个数组。

到目前为止,这是我想出的。所以基本上我想打印 a,d,f

def something(paramOne):
    result = [paramOne[1,4,6]]
    return result

print(something(['a','b','c','d','e','f']))

标签: pythonarraysfunctionparameters

解决方案


问题:任何可迭代的索引应该是一个整数,你给出一个列表

修复:遍历列表,如果索引(i+1 使其成为 1 索引)在我们的列表中,则将其添加到结果中

def something(paramOne):
    # result = [paramOne[1,4,6]] >>> Index of any iterable should be an integer, you are giving a list
    result = [v for i,v in enumerate(paramOne) if i+1 in [1,4,6]] # here i am going through the list and if the index(i+1 to make it 1 indexed) is in our list add it to the result
    return result

print(something(['a','b','c','d','e','f']))
['a', 'd', 'f']

推荐阅读