python - 如何使用输入数组参数定义函数
问题描述
我想用一个输入数组参数创建一个函数,然后从第 1、4 和 6 个元素返回一个数组。
到目前为止,这是我想出的。所以基本上我想打印 a,d,f
def something(paramOne):
result = [paramOne[1,4,6]]
return result
print(something(['a','b','c','d','e','f']))
解决方案
问题:任何可迭代的索引应该是一个整数,你给出一个列表
修复:遍历列表,如果索引(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']
推荐阅读
- swiftui - SwiftUI:有一个按钮自己改变吗?
- c++ - 在 mac 上编译 hello world wxWidget 程序时找不到“wx/wx.h”文件
- spring-boot - SpringBoot 将参数传递给 CommandLineRunner
- javascript - 删除后如何获取div的数量?
- javascript - 单击时我的导航栏中只有一个 Li 加粗的逻辑:React + Typescript
- python - 无法在 Windows 10 上的 python 3.7.6 上导入 tensorflow
- c# - 错误:尝试在windoes表单c#程序中保存数据时,“:”处或附近出现42601语法错误
- c++ - 使用 unique_ptr 值从 unordered_map 移动的最佳方法
- logback - Playspec 没有选择记录器配置
- python - 如何将索引转换为日期时间