Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 要将列表中的项目提取并转换为小于特定数字的数字打印吗_Python_Python 3.x_List_Computer Science - Fatal编程技术网

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

Python 要将列表中的项目提取并转换为小于特定数字的数字打印吗,python,python-3.x,list,computer-science,Python,Python 3.x,List,Computer Science,我正在写一个程序,它有两个参数,一组数字1-10。一个n=6的变量。 我创建了一个函数,它接受这两个参数,并将小于6的值返回到一个新列表中。但是我试着打印小于6的数字。它正在打印索引号。 是否有一种快速修复或简单的方法将input_列表中的项目转换为整数以打印结果 它正在打印[0,1,2,3,4] 但我希望它打印[1,2,3,4,5] 谢谢你的帮助 *Python3代码* 这个程序接受两个参数,一个数字和一个列表。 一个函数应该返回一个比该数字小的所有数字的列表 def main():

我正在写一个程序,它有两个参数,一组数字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()
您只需执行以下操作:

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

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

for item in input_lsit:
    if n > item:
        result.append(item)
这样,您就可以迭代
input\u列表中的元素,并将小于
n的元素存储在列表
result

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

def smaller_than_n_list(input_list,n):
    return [e for e in input_list if e < n]
def小于列表(输入列表,n):
返回[e,如果e
change result.append(num)to result.append(input_list[num])当您在result中追加索引时,不是现在的值谢谢大家提供的信息性回复。谢谢您的帮助和帮助@请不要对您的问题添加评论以表示“谢谢”。评论是为了要求澄清,留下建设性的批评,或添加相关但次要的附加信息,而不是为了社交。如果你想说“谢谢”,那么就投票或接受那个人的答案,或者简单地通过给别人的问题提供一个很好的答案来提前回答。