加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

在python中分发一个列表

发布时间:2020-12-20 12:06:25 所属栏目:Python 来源:网络整理
导读:假设我有一个配置字典: config = {'A': 3,'B': 4,'C': 2} 我如何平展分发(散布)列表,如下所示: (逐个追加到结果列表中仍然是所有配置的结尾) result = ['A','B','C','A','B'] 另一个例子: config = {'A': 3,'B': 1}result = ['A','A']config = {'A': 2,'B
假设我有一个配置字典:

config = {'A': 3,'B': 4,'C': 2}

我如何平展分发(散布)列表,如下所示:
(逐个追加到结果列表中仍然是所有配置的结尾)

result = ['A','B','C','A','B']

另一个例子:

config = {'A': 3,'B': 1}
result = ['A','A']

config = {'A': 2,'B': 2}
result = ['A','B']

解决方法

from itertools import izip_longest as izip_l,chain
config = {'A': 3,'C': 2}

# Reconstruct the list of lists
expanded = [[k] * config[k] for k in config]

# Just zip them and ignore the None
print[item for item in chain.from_iterable(izip_l(*expanded)) if item]

如果计数太大,如果你担心性能和消耗的内存,你可以使用repeat而不是重建列表列表,就像这样

from itertools import izip_longest as izip_l,chain,repeat
expanded = [repeat(k,config[k]) for k in config]

休息都是一样的

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读