用一个字符串列表乘以一个整数列表

5
假设有两个列表:
l1 = [2,2,3]
l2 = ['a','b','c']

我想知道如何找到这两个数的积,使得输出结果为:

#output: ['a','a','b','b','c','c','c']

如果我执行:

l3 = []
for i in l2:
    for j in l1:
        l3.append(i)

我得到:

['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c']

这是错误的,我想知道我在哪里犯了错?

8个回答

5
您可以利用sum函数(滥用):
>>> sum([[a] * b for a, b in zip(l2, l1)], [])
['a', 'a', 'b', 'b', 'c', 'c', 'c']

4
在Python中, 您可以直接用一个数字 乘以 一个字符串:
l1 = [2,2,3]
l2 = ['a','b','c']


res = [c for a, b in zip(l2, l1) for c in a * b]
print(res)

输出

['a', 'a', 'b', 'b', 'c', 'c', 'c']

作为函数式编程的替代方案:
from itertools import chain
from operator import mul

res = list(chain.from_iterable(map(mul, l2, l1)))

print(res)

输出结果

['a', 'a', 'b', 'b', 'c', 'c', 'c']

3
只有当字符串为单个字符时,for c in a * b 才有效。 - tobias_k

4
在列表 l1 中有 3 个元素,因此每次执行循环 for j in l1: 都会迭代 3 次。
尝试:
out = [b for a, b in zip(l1, l2) for _ in range(a)]
print(out)

输出:

['a', 'a', 'b', 'b', 'c', 'c', 'c']

3
如果将一个整数与字符串相乘,它就会重复该字符串: 例如,'a' * 3 输出 'aaa'
因此,使用列表推导式:
out = [b for a, b in zip(l1, l2) for _ in range(a)]
print(out)

输出:

['a', 'a', 'b', 'b', 'c', 'c', 'c']

2

仅使用一个for循环:

res = []
for i in range(len(l1)): res += [l2[i]] * l1[i]
print(res)

输出:

['a', 'a', 'b', 'b', 'c', 'c', 'c']

2
你可以使用itertools.repeat来重复你想要的字符串:
>>> from itertools import repeat

>>> l1 = [2, 2, 3]
>>> l2 = ['a', 'b', 'c']

>>> [v for n, s in zip(l1, l2) for v in repeat(s, n)]
['a', 'a', 'b', 'b', 'c', 'c', 'c']

即使l2的子字符串有多个字符,这种方式也可以实现。

我喜欢这种方式,因为它更易读(至少对我来说是这样)!


1

你可以这样做:

l1 = [2,2,3]
l2 = ['a','b','c']

# You can zip the two lists together then create a list by multiplying 
#their elements then converting back to a list like so :
l = [ list([s] * i) for i, s in zip(l1, l2)]
output = [item for sublist in l for item in sublist]
output

list(s * i) only works for single characters; better use [s] * i - tobias_k
是的,在非单个字符字符串的情况下,这是一种更通用的方法。 - Said Taghadouini

0
嗨,William,这里有很好的答案。我尝试创建一个函数,它将接受您的数字列表和字符列表,并生成一个新列表,其中每个字符都添加了您在数字列表中指定的数量。
enter code here
l1 = [2,2,3]
l2 = ['a','b','c']

def new_list(num_list, char_list):
    l3 = []
    for i in range(0,len(num_list)):
        amount_to_append = num_list[i]
        item_to_be_added = char_list[i]
        for i in range(0,amount_to_append):
            l3.append(item_to_be_added)
    return l3

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接