我有
list = [a, b, c, d]
和
numbers = [2, 4, 3, 1]
我想得到一个类型列表:
new_list = [a, a, b, b, b, b, c, c, c, d]
这是我到目前为止:
new_list=[] for i in numbers: for x in list: for i in range(1,i+1): new_list.append(x)
Moses Koledo.. 10
这是使用zip
字符串乘法和列表理解的一种方法:
lst = ['a', 'b', 'c', 'd'] numbers = [2 , 4, 3, 1] r = [x for i, j in zip(lst, numbers) for x in i*j] print(r) # ['a', 'a', 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'd']
使用Python时要注意名称的选择.一个名称list
使内置列表功能无法使用.
如果项目lst
不是字符串,您只需使用嵌套理解range
,即可复制列表中的项目.
这是使用zip
字符串乘法和列表理解的一种方法:
lst = ['a', 'b', 'c', 'd'] numbers = [2 , 4, 3, 1] r = [x for i, j in zip(lst, numbers) for x in i*j] print(r) # ['a', 'a', 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'd']
使用Python时要注意名称的选择.一个名称list
使内置列表功能无法使用.
如果项目lst
不是字符串,您只需使用嵌套理解range
,即可复制列表中的项目.
嵌套列表理解有效:
L = ['a','b','c','d'] numbers = [2, 4, 3, 1] >>> [x for x, number in zip(L, numbers) for _ in range(number)] ['a', 'a', 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'd']
"子循环" for _ in range(number)
重复值number
时间.这里L
可以容纳任何对象,而不仅仅是字符串.
例:
L = [[1, 2, 3],'b','c', 'd'] numbers = [2, 4, 3, 1] [x for x, number in zip(L, numbers) for _ in range(number)] [[1, 2, 3], [1, 2, 3], 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'd']
但这会使子列表变平:
[x for i, j in zip(L, numbers) for x in i*j] [1, 2, 3, 1, 2, 3, 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'd']
不完全是理想的结果.
作为任何对象(不仅是字符串)的通用方法,可以 itertools.repeat()
在生成器表达式中使用:
def repeat_it(lst, numbers): return chain.from_iterable(repeat(i, j) for i, j in zip(lst, numbers))
演示:
In [13]: from itertools import repeat, chain In [21]: lst=[5,4,6,0] In [22]: list(repeat_it(lst, numbers)) Out[22]: [5, 5, 4, 4, 4, 4, 6, 6, 6, 0] In [23]: lst=['a','b','c','d'] In [24]: list(repeat_it(lst, numbers)) Out[24]: ['a', 'a', 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'd']
这是3种主要方法的基准。请注意,最后一个onley适用于字符串:
In [49]: lst = lst * 1000 In [50]: numbers = numbers * 1000 In [51]: %timeit list(chain.from_iterable(repeat(i, j) for i, j in zip(lst, numbers))) 1 loops, best of 3: 8.8 s per loop In [52]: %timeit [x for x, number in zip(lst, numbers) for _ in range(number)] 1 loops, best of 3: 12.4 s per loop In [53]: %timeit [x for i, j in zip(lst, numbers) for x in i*j] 1 loops, best of 3: 7.2 s per loop