python - 说列表 = [9, 8, 9, 10]。例如,我如何找到 9 的位置?
问题描述
功能
def find_value(num_list, target):
target_loc = [] # list to store the location of the target
condition = True
while condition == True:
for target in num_list:
if target in num_list:
index = num_list.index(target)
target_loc.append(index)
condition = True
else:
condition = False
return target_loc
主程序:
num_list = keep_positive_numbers()
print()
print("List entered: ", num_list)
print()
target = int(input("Enter target = "))
print()
list = find_value(num_list, target)
print("Target exists at location(s): ", list)
输出
输入正整数:9 输入正整数:9 输入正整数:8 输入正整数:0
输入列表:[9, 9, 8]
输入目标 = 7
目标存在于以下位置:[0, 0, 2]
解决方案
def find_value(num_list, target):
return [i for i, x in enumerate(num_list) if x == target]
find_value([9, 8, 9, 10], 9)
# [0, 2]
或者,如果您想要显式循环,请在索引上使用 for 循环:
def find_value(num_list, target):
target_loc = [] # list to store the location of the target
for i in range(len(num_list)):
if target == num_list[i]:
target_loc.append(i)
return target_loc
您必须一一检查索引。list.index
总是返回第一个。
推荐阅读
- python - 在服务器上执行 python 脚本
- javascript - 从 Github 克隆后无法运行 React App
- amazon-web-services - 图像未从 codebuild 发送到 ecr 而 buildspec 没有错误
- mongodb - MongoDB集群时间与挂钟时间相差太远
- javascript - 在关闭浏览器窗口/选项卡时触发哪个事件但在重新加载时不触发?
- c# - 从静态 LOCAL 文件启动 Blazor Web 程序集
- python - 从不同目录导入模块时导入错误
- sas - 我如何选择关于重复的前 5 个观察值?
- kotlin - Axonframework 事件调度程序不断地重新运行我的事件
- sql - 如何在查询 SELECT 中进行数学运算?