我正在写一个程序,它有两个参数,一组数字1-10。一个n=6的变量。 我创建了一个函数,它接受这两个参数,并将小于6的值返回到一个新列表中。但是我试着打印小于6的数字。它正在打印索引号。 是否有一种快速修复或简单的方法将input_列表中的项目转换为整数以打印结果
它正在打印[0,1,2,3,4] 但我希望它打印[1,2,3,4,5]
谢谢你的帮助
*Python3代码*
这个程序接受两个参数,一个数字和一个列表。 一个函数应该返回一个比该数字小的所有数字的列表
def main():
#initialize a list of numbers
input_list = [1,2,3,4,5,6,7,8,9,10]
n = 6
print("List of Numbers:")
print(input_list)
results_list = smaller_than_n_list(input_list,n)
print("List of Numbers that are smaller than 6:")
print(results_list)
def smaller_than_n_list(input_list,n):
# create an empty list
result = []
for num in range(len(input_list)):
if n > input_list[num]:
result.append(num)
return result
main()
python中的索引从
0
开始,当您在range(len(input_list))
上迭代时,您正在访问和存储索引,以便获得[0,1,2,3,4],要修复此问题,您可以使用:通过这种方式,您将迭代来自
input_list
的元素,并将小于n
的元素存储在列表中result
此外,您还可以使用列表:
您只需执行以下操作:
相关问题 更多 >
编程相关推荐