簡體   English   中英

list.extend和list comprehension

[英]list.extend and list comprehension

當我需要在列表中添加幾個相同的項目時,我使用list.extend:

a = ['a', 'b', 'c']
a.extend(['d']*3)

結果

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

但是,如何與列表理解類似?

a = [['a',2], ['b',2], ['c',1]]
[[x[0]]*x[1] for x in a]

結果

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

但我需要這個

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

有任何想法嗎?

堆疊式LC。

[y for x in a for y in [x[0]] * x[1]]
>>> a = [['a',2], ['b',2], ['c',1]]
>>> [i for i, n in a for k in range(n)]
['a', 'a', 'b', 'b', 'c']

一個itertools方法:

import itertools

def flatten(it):
    return itertools.chain.from_iterable(it)

pairs = [['a',2], ['b',2], ['c',1]]
flatten(itertools.repeat(item, times) for (item, times) in pairs)
# ['a', 'a', 'b', 'b', 'c']

如果您更喜歡擴展列表推導:

a = []
for x, y in l:
    a.extend([x]*y)
import operator
a = [['a',2], ['b',2], ['c',1]]
nums = [[x[0]]*x[1] for x in a]
nums = reduce(operator.add, nums)
>>> a = [['a',2], ['b',2], ['c',1]]
>>> sum([[item]*count for item,count in a],[])
['a', 'a', 'b', 'b', 'c']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM