创建列表或将列表追加到列表(如果已经存在)的有效方法? [英] Efficient way to either create a list, or append to it if one already exists?

查看:85
本文介绍了创建列表或将列表追加到列表(如果已经存在)的有效方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在遍历一堆具有多对多相关性的元组,并且我想制作一个字典,其中(a,b)的每个b都有一个对应于b的所有a的列表. .在元组摘要循环中,每次都在字典的键b处测试列表,然后寻找a,然后附加a(如果还不存在)似乎很尴尬;但我还没有找到更好的方法.是否存在?还有其他更漂亮的方法吗?

I'm going through a whole bunch of tuples with a many-to-many correlation, and I want to make a dictionary where each b of (a,b) has a list of all the a's that correspond to a b. It seems awkward to test for a list at key b in the dictionary, then look for an a, then append a if it's not already there, every single time through the tuple digesting loop; but I haven't found a better way yet. Does one exist? Is there some other way to do this that's a lot prettier?

推荐答案

请参见 setdefault()方法的文档:

See the docs for the setdefault() method:

setdefault(key [,默认])
如果键是 在字典中,返回其值. 如果不是,请插入值为 默认值并返回默认值.默认 默认为无.

setdefault(key[, default])
If key is in the dictionary, return its value. If not, insert key with a value of default and return default. default defaults to None.

您可以将其用作单个调用,如果存在b,则将得到b;如果尚不存在,则将b设置为空列表-无论哪种方式,都返回b:

You can use this as a single call that will get b if it exists, or set b to an empty list if it doesn't already exist - and either way, return b:

>>> key = 'b'
>>> val = 'a'
>>> print d
{}
>>> d.setdefault(key, []).append(val)
>>> print d
{'b': ['a']}
>>> d.setdefault(key, []).append('zee')
>>> print d
{'b': ['a', 'zee']}

通过一个简单的"not in"检查将其合并,您已经完成了三行的工作:

Combine this with a simple "not in" check and you've done what you're after in three lines:

>>> b = d.setdefault('b', [])
>>> if val not in b:
...   b.append(val)
... 
>>> print d
{'b': ['a', 'zee', 'c']}

这篇关于创建列表或将列表追加到列表(如果已经存在)的有效方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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