list.extend和list理解 [英] list.extend and list comprehension

查看:92
本文介绍了list.extend和list理解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我需要将几个相同的项目添加到列表时,我使用list.extend:

When I need to add several identical items to the list I use list.extend:

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

结果

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

但是,如何与列表理解类似?

But, how to do the similar with list comprehension?

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]]

这篇关于list.extend和list理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆