要将列表中的项目提取并转换为小于特定数字的数字打印吗

2024-03-29 08:25:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在写一个程序,它有两个参数,一组数字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()

Tags: of函数程序列表input参数maindef
2条回答

python中的索引从0开始,当您在range(len(input_list))上迭代时,您正在访问和存储索引,以便获得[0,1,2,3,4],要修复此问题,您可以使用:

for item in input_lsit:
    if n > item:
        result.append(item)

通过这种方式,您将迭代来自input_list的元素,并将小于n的元素存储在列表中result

此外,您还可以使用列表:

def smaller_than_n_list(input_list,n):
    return [e for e in input_list if e < n]

您只需执行以下操作:

def smaller_than_n_list(input_list, n):
    result = []
    for i in input_list: #i will be equal to 1, then, 2 ... to each value of your list
        if n > i:
            result.append(i) #it will append the value, not the index
    return result

相关问题 更多 >