简体   繁体   English

创建一个数字的倍数列表

[英]Create a list of multiples of a number

Problem:问题:

List of Multiples倍数列表
Create a Python 3 function that takes two numbers (value, length) as arguments and returns a list of multiples of value until the size of the list reaches length.创建一个 Python 3 函数,该函数接受两个数字(值、长度)作为参数并返回值的倍数列表,直到列表的大小达到长度为止。

Examples例子
list_of_multiples(value=7, length=5)[7, 14, 21, 28, 35] list_of_multiples(value=7, length=5)[7, 14, 21, 28, 35]

list_of_multiples(value=12, length=10)[12, 24, 36, 48, 60, 72, 84, 96, 108, 120] list_of_multiples(value=12, length=10)[12, 24, 36, 48, 60, 72, 84, 96, 108, 120]

list_of_multiples(value=17, length=6)[17, 34, 51, 68, 85, 102] list_of_multiples(value=17, length=6)[17, 34, 51, 68, 85, 102]

def multiples (value,length):
    """
    Value is number to be multiply
    length is maximum number of iteration up to
    which multiple required.
    """
    for i in range(length):
        out=i
    return i

Most Pythonic Way最 Pythonic 的方式

def multiples(value, length):
    return [*range(value, length*value+1, value)]

print(multiples(7, 5))
# [7, 14, 21, 28, 35]
print(multiples(12, 10))
# [12, 24, 36, 48, 60, 72, 84, 96, 108, 120]
print(multiples(17, 6))
# [17, 34, 51, 68, 85, 102]

Pythonic way: Pythonic方式:

def multiples(value, length):
    return [value * i for i in range(1, length + 1)]


print(multiples(7, 5))
# [7, 14, 21, 28, 35]
print(multiples(12, 10))
# [12, 24, 36, 48, 60, 72, 84, 96, 108, 120]
print(multiples(17, 6))
# [17, 34, 51, 68, 85, 102]
def multiples(value, length): list_multiples = [] i = 0 while i < length: list_multiples.append(value*(i+1)) i+=1 return list_multiples

The best answer for small values of length (< 100) is given by Nite Block . Nite Block给出了小length值 (< 100) 的最佳答案。

However, in case length becomes bigger, using numpy is significantly faster than python loops:但是,如果length变大,使用 numpy 比 python 循环要快得多:

numpy.arange(1, length+1) * value

With a length of 1000, python loops take almost 4 times longer than numpy.长度为 1000 时,python 循环的时间几乎是 numpy 的 4 倍。 See code below:见下面的代码:

import timeit

testcode_numpy = ''' 
import numpy
def multiples_numpy(value, length):
    return numpy.arange(1, length+1) * value
multiples_numpy(5, 1000)
'''

testcode = ''' 
def multiples(value, length):
    return [*range(value, length*value+1, value)]
multiples(5, 1000)
'''

print(timeit.timeit(testcode_numpy))
print(timeit.timeit(testcode))

# Result:
# without numpy: 9.7 s
# with numpy: 2.4 s

The easy / not in-line way would be :简单/不在线的方式是:

def multiples(value, length):
    l = []
    for i in range(1, length+1):
        l.append(value*i)
    return l

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

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