如何用整数列表乘以字符串列表?

时间:2018-02-17 02:11:50

标签: python python-3.x

我希望乘以a * b

a = ['a', 'e', 'y']    
b = [3, 2, 1]

并获得:

c = ['a', 'a', 'a', 'e', 'e', 'y']

7 个答案:

答案 0 :(得分:2)

可以使用sum()zip()list comprehension来完成:

代码:

c = sum([[s] * n for s, n in zip(a, b)], [])

测试代码:

a = ['a', 'e', 'y']
b = [3, 2, 1]

c = sum([[s] * n for s, n in zip(a, b)], [])
print(c)

结果:

['a', 'a', 'a', 'e', 'e', 'y']

答案 1 :(得分:2)

zip()是你的朋友:

a = ['a', 'e', 'y']

b = [3, 2, 1]

c = []
for x, y in zip(a, b):
    c.extend([x] * y)

print(c)
# ['a', 'a', 'a', 'e', 'e', 'y']

itertools.chain.from_iterable()

from itertools import chain

c = list(chain.from_iterable([x] * y for x, y in zip(a, b)))

print(c)
# ['a', 'a', 'a', 'e', 'e', 'y']

答案 2 :(得分:1)

你可以试试这个:

a = ['a', 'e', 'y']    
b = [3, 2, 1]
new_list = [i for b in [[c]*d for c, d in zip(a, b)] for i in b]

输出:

['a', 'a', 'a', 'e', 'e', 'y']

答案 3 :(得分:1)

在我看来,最基本的循环方法是:

a = ['a', 'e', 'y']
b = [3, 2, 1]
c = []

for i in range(len(a)):
    c.extend(list(a[i]*b[i]))

答案 4 :(得分:0)

喜欢一个班轮:

>>> from itertools import chain
>>> a = ['a', 'e', 'y']
>>> b = [3, 2, 1]
>>> c = list(chain(*[x*y for x,y in zip(a,b)]))
>>> c
['a', 'a', 'a', 'e', 'e', 'y']

答案 5 :(得分:0)

您实际上并不需要导入任何模块,正如我在评论中所说,请考虑阅读Python文档。

a = ['a', 'e', 'y']    
b = [3, 2, 1]
c = []

for i in range(len(a)):
    c += [a[i]] * b[i]

print(c)

答案 6 :(得分:0)

通过 collections.Counter ,您可以这样做: -

试试这个: -

from collections import Counter
a = ['a', 'e', 'y']    
b = [3, 2, 1]
d = {x:y for x,y in zip(a,b)}
c = Counter(d)
print(list(c.elements())) #your output