簡體   English   中英

在列表的每個項目之間加入元素 - python

[英]Join element between each item of a list - python

我想在這種情況下加入一個元素,它是列表的每個元素之間的“*”,但不是在第一個 position 和最后一個 position

我怎樣才能做到這一點?

代碼:

import math
def decompose(n:int):
    
    factors = []
    
    
    if n < 2:
        return False
    
    for d in range(2, int(math.sqrt(n)) +1):
        
        if n % d == 0:
            factors.append(d)
            print(factors)
            
    factors = str(factors)
    
            
    print(f"The decomposition of {number5} in prime factor is" + '*'.join(str(factors)))       
    return True
    
number5 = int(input('Chose a number:'))


print(decompose(number5))

它打印這個:

Decomposition of 45 in prime factor is [*3*,* *5*]

但這不是我想要的,我想要在第一個和最后一個 position 中不帶逗號且不帶*的數字

這邊走:

def decompose(n: int):
    factors = []

    if n < 2:
        return False

    d = 2
    while d <= n:
        while n % d == 0:
            factors.append(str(d))
            n //= d
        d += 1
    if n > 1:
        factors.append(str(n))

    print(f"The decomposition of {number5} in prime factor is " + '*'.join(factors))
    return True


number5 = int(input('Chose a number:'))

print(decompose(number5))

我改變了什么:

  • 分解算法。 現在它計算多個乘數。
  • factors現在是List[str] ,因此可以輕松執行join

從方法返回因子然后將列表迭代為字符串值的一種好方法。

import math


def decompose(n: int):
    factors = []
    if n < 2:
        return False
    for d in range(2, int(math.sqrt(n)) + 1):
        if n % d == 0:
            factors.append(d)
    return factors


number5 = int(input('Choose a number:'))
factors = decompose(number5)
print(f"The decomposition of {number5} in prime factor is " + '*'.join(
    [str(i) for i in factors]))

Output:

Choose a number:45
The decomposition of 45 in prime factor is 3*5

有不同的方法可以做到這一點,下面的解釋只是一種方法。

在這一行:

factors = str(factors)

您正在將列表本身變成一個字符串。 如果要加入列表中的每個項目,則需要將它們轉換為字符串。 您可以通過使用列表推導來做到這一點:

factors = [str(x) for x in factors]

然后我會將打印分解的行更改為:

print(f"The decomposition of {number5} in prime factor is {'*'.join(factors)}.")

因此,對於輸入 45,output 應該是(除其他外)“45 的素數分解是 3*5”。

編輯:您可能想查看代碼的 rest,3*5 不是 45 的主要分解。

暫無
暫無

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

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