簡體   English   中英

如何將數學運算應用於python中列表中的每個數字?

[英]How to apply math operations to each number from a list in python?

我是python的初學者(一周)。 在這里,我嘗試打印60的所有素因子的列表。但對於第19行,我收到以下錯誤: TypeError:%支持的操作數類型:'float'和'list'

代碼:

whylist = []
factor = []
boom = []
primefactor = []
n = 60
j = (list(range(1, n, 1)))



for numbers in j:
    if n%numbers == 0:
        whylist.append(numbers)
        for everynumber in whylist:
            factor.append(everynumber)

for things in factor:
    u = (list(range(1, things, 1)))
    d = float(things)
    if d%u == 0:
        boom.append(things)
    if len(boom) == 1:
        for every in boom:
            primefactor.append(every)
print(primefactor)

我究竟做錯了什么?

要將數學運算應用於列表中的每個元素,可以使用列表推導:

new_list = [ x%num for x in old_list]

還有其他方法可以做到這一點。 有時人們會使用map

new_list = map(lambda x: x%num, old_list)

但是大多數人更喜歡第一種形式,這種形式通常比使用lambda更有效率和清晰度(當你剛開始學習python時可能有點混亂)。

編輯

這是你正在嘗試的遞歸實現:

def factorize(n):
    out=[]
    for i in range(2,n):
        if(n%i == 0): #first thing to hit this is always prime
            out.append(i) #add it to the list
            out+=factorize(n/i)  #get the list of primes from the other factor and append to this list.
            return out
        else:
            return [n] # n%i was never 0, must be prime.

print factorize(2000)

另一種選擇是使用numpy數組而不是列表。

import numpy as np
j = np.arange(1,n,1)
rem = np.mod(j,num)

numpy將為您負責廣播業務。 它也應該比列表推導或地圖更快。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM