串联字典值(列表) [英] Concatenating dict values, which are lists

查看:63
本文介绍了串联字典值(列表)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下dict对象:

Suppose I have the following dict object:

test = {}
test['tree'] = ['maple', 'evergreen']
test['flower'] = ['sunflower']
test['pets'] = ['dog', 'cat']

现在,如果我运行test['tree'] + test['flower'] + test['pets'],我会得到结果:

Now, if I run test['tree'] + test['flower'] + test['pets'], I get the result:

['maple', 'evergreen', 'sunflower', 'dog', 'cat']

这就是我想要的.

但是,假设我不确定dict对象中有哪些键,但是我知道所有值都是列表.有没有类似sum(test.values())的方法或可以运行以达到相同结果的方法?

However, suppose that I'm not sure what keys are in the dict object but I know all the values will be lists. Is there a way like sum(test.values()) or something I can run to achieve the same result?

推荐答案

几乎给出了问题的答案: sum(test.values())只会失败,因为默认情况下它假定您要添加项目到0的起始值,当然,您不能将list添加到int.但是,如果您明确知道起始值,它将起作用:

You nearly gave the answer in the question: sum(test.values()) only fails because it assumes by default that you want to add the items to a start value of 0—and of course you can't add a list to an int. However, if you're explicit about the start value, it will work:

 sum(test.values(), [])

这篇关于串联字典值(列表)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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