Python 根据动态值将整数多次追加到for循环中的列表

Python 根据动态值将整数多次追加到for循环中的列表,python,Python,我有一个动态字符串数量,它可以改变。我有一个循环将产品添加到列表中(产品是一个整数)。我需要实现的目标是将相同的产品添加到列表中,数量等于 在我的示例中,我需要将一个产品添加到产品列表中5次 product_list = [] for product in products: qty = '5' # dynamic , will change each time when entering the loop and its a string product_list.appen

我有一个动态字符串数量,它可以改变。我有一个循环将产品添加到列表中(产品是一个整数)。我需要实现的目标是将相同的产品添加到列表中,数量等于

在我的示例中,我需要将一个产品添加到产品列表中5次

product_list = []

for product in products:
    qty = '5' # dynamic , will change each time when entering the loop and its a string
    product_list.append(product) # 5 times
有办法吗?因为我无法理解

使用
范围

Ex:

product_list = []

for product in products:
    qty = 5 # dynamic , will change each time when entering the loop
    for _ in range(qty):
        product_list.append(product) # 5 times
要多次重复列表项,请执行以下操作:

使用方便的功能也可以达到同样的效果:

from itertools import repeat

product_list = []

for product in (1, 2, 3):
    qty = '5' # dynamic , will change each time when entering the loop
    product_list.extend(itertools.repeat(product, int(qty)))

输出(两种方法相同):


以下是一个尽可能符合您要求的解决方案:

product_list = []
products = ["product_one", "product_two"]


for product in products:
    qty = '5'
    qty = int(qty)
    for counter in range(qty):
        product_list.append(product)

print(product_list)
print(product_list)
[1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3]
product_list = []
products = ["product_one", "product_two"]


for product in products:
    qty = '5'
    qty = int(qty)
    for counter in range(qty):
        product_list.append(product)

print(product_list)