[英]Multiplying strings in a list by numbers from another list, element by element
I have two lists, ['A', 'B', 'C', 'D']
and [1, 2, 3, 4]
.我有两个列表,
['A', 'B', 'C', 'D']
和[1, 2, 3, 4]
。 Both lists will always have the same number of items.两个列表将始终具有相同数量的项目。 I need to multiply each string by its number, so the final product I am looking for is:
我需要将每个字符串乘以它的数字,所以我要寻找的最终产品是:
['A', 'B', 'B', 'C', 'C', 'C', 'D', 'D', 'D', 'D']
Nested list comprehension works too:嵌套列表理解也有效:
>>> l1 = ['A', 'B', 'C', 'D']
>>> l2 = [1, 2, 3, 4]
>>> [c for c, i in zip(l1, l2) for _ in range(i)]
['A', 'B', 'B', 'C', 'C', 'C', 'D', 'D', 'D', 'D']
In above zip
returns (char, count)
tuples:在上面的
zip
返回(char, count)
元组:
>>> t = list(zip(l1, l2))
>>> t
[('A', 1), ('B', 2), ('C', 3), ('D', 4)]
Then for every tuple the second for
loop is executed count
times to add the character to the result:然后对于每个元组,第二个
for
循环被执行count
次以将字符添加到结果中:
>>> [char for char, count in t for _ in range(count)]
['A', 'B', 'B', 'C', 'C', 'C', 'D', 'D', 'D', 'D']
I would use itertools.repeat
for a nice, efficient implementation:我会使用
itertools.repeat
来实现一个不错的、高效的实现:
>>> letters = ['A', 'B', 'C', 'D']
>>> numbers = [1, 2, 3, 4]
>>> import itertools
>>> result = []
>>> for letter, number in zip(letters, numbers):
... result.extend(itertools.repeat(letter, number))
...
>>> result
['A', 'B', 'B', 'C', 'C', 'C', 'D', 'D', 'D', 'D']
>>>
I also think it is quite readable.我也觉得可读性很强。
The code is pretty straight forward, see inline comments代码非常简单,请参阅内联注释
l1 = ['A', 'B', 'C', 'D']
l2 = [1, 2, 3, 4]
res = []
for i, x in enumerate(l1): # by enumerating you get both the item and its index
res += x * l2[i] # add the next item to the result list
print res
OUTPUT输出
['A', 'B', 'B', 'C', 'C', 'C', 'D', 'D', 'D', 'D']
You use zip()
to do it like this way:您可以使用
zip()
以这种方式执行此操作:
a = ['A', 'B', 'C', 'D']
b = [1, 2, 3, 4]
final = []
for k,v in zip(a,b):
final += [k for _ in range(v)]
print(final)
Output:输出:
>>> ['A', 'B', 'B', 'C', 'C', 'C', 'D', 'D', 'D', 'D']
Or you can do it, too, using zip()
and list comprehension
:或者你也可以使用
zip()
和list comprehension
来做到这一点:
a = ['A', 'B', 'C', 'D']
b = [1, 2, 3, 4]
final = [k for k,v in zip(a,b) for _ in range(v)]
print(final)
Output:输出:
>>> ['A', 'B', 'B', 'C', 'C', 'C', 'D', 'D', 'D', 'D']
You can use NumPy and then convert the NumPy array to a list:您可以使用 NumPy 然后将 NumPy 数组转换为列表:
letters = ['A', 'B', 'C', 'D']
times = [1, 2, 3, 4]
np.repeat(letters, times).tolist()
#output
['A', 'B', 'B', 'C', 'C', 'C', 'D', 'D', 'D', 'D']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.