简体   繁体   English

如何制作从1开始的N个连续奇数的列表

[英]How to make a list of N consecutive odd numbers starting from 1

I need to write a function that generates a list of n odd numbers, starting at 1. If input is 12, output should be [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23] .我需要编写一个函数来生成一个包含 n 个奇数的列表,从 1 开始。如果输入是 12,则输出应该是[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23] If input is 10 , output should be [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]如果输入是10 ,输出应该是[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

Almost..几乎..

def odd(n):
    nums = []
    for i in range(1, 2*n, 2):
        nums.append(i)
    return nums

we know that every other number is odd, so we have to "count" up to 2*n to include all of them.我们知道每隔一个数字都是奇数,所以我们必须“计数”到2*n才能包括所有这些。 The range function takes a third argument that indicates how many elements to skip in each iteration. range函数接受第三个参数,该参数指示在每次迭代中要跳过多少个元素。

def odd(n):
    return list(range(1, 2*n, 2))

print(odd(10))
print(odd(12))

The output:输出:

[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]                                                                                                                           
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23]    

Code with list comprehenssion :-具有list comprehenssion代码:-

def odd(n):
    return [num for num in range(1, n*2+1,2)]
odd(10)

Output输出

[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

range(..) can take a third parameter that is the step the amount the value increments each iteration. range(..)可以采用第三个参数,该参数是值每次迭代增量的step The last item of a list with the first n odd elements, is 2×n-1 , so we can write this as:具有前n 个奇数元素的列表的最后一项是2×n-1 ,因此我们可以将其写为:

def odd(n):
    return list(range(1, 2*n, 2))

Why not just:为什么不只是:

def odd(n):
    return list(range(1, n * 2, 2))

Or with numpy或者用numpy

import numpy as np
def odd(n):
   return np.arange(1, 2*n, 2)


odd(10) -> array([ 1,  3,  5,  7,  9, 11, 13, 15, 17, 19])
odd(12) -> array([ 1,  3,  5,  7,  9, 11, 13, 15, 17, 19, 21, 23])

You can use this also:-您也可以使用它:-

def odd(n):
    nums = []
    for i in range(1, n*2+1):
        if i%2==0:
            pass
        else:
            nums.append(i)
    return nums
odd(10)

Output输出

[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
def f(n):
    return[i for i in range(1,n*2,2)]

or或者

def E(n):
    list=[]
    list.extend(i for i in range(1,2*n,2))
    return(list)

With lambda AND numpy .使用lambdanumpy With the help of lambda you can write function in one line AND numpy.arange is like range() but it returns an array:-lambda的帮助下,您可以在一行中编写函数并且numpy.arange就像range()但它返回一个数组:-

import numpy as np  # Importing numpy module
odd = lambda num: np.arange(1,num*2+1,2)   
odd(10)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM