如何在 python 中将值插入到列表中..有一些额外的条件
嗨,我有一个这样的元组列表:
bigrams = [ ('wealth', 'gain'), ('gain', 'burnt'), ('burnt', 'will'), ('will', 'fire ') ]
,我希望将每个单独的元组作为字典键附加到字典中。
我希望格式看起来像这样。
dict = {"wealth-gain": value, "gain-burnt": value ......}
我将如何创建一个循环来遍历二元组列表中的每个元组并将其附加到字典中?
这就是我基本上所拥有的,
For word in bigrams:
dict[(0+"-"+1) = dict
我想获取每个元组并在元组中的每个单词之间添加一个“-”,然后将其附加到字典中?
有什么想法如何做到这一点?
此外,如果要附加到字典中的二元组与字典中已有的二元组匹配,我不想将该二元组添加到字典中。相反,我想增加字典中已有的二元组的值。 有什么想法如何做到这一点吗?
谢谢。
hi i have a list of tuples like this:
bigrams = [ ('wealth', 'gain'), ('gain', 'burnt'), ('burnt', 'will'), ('will', 'fire') ]
and i wish to append each individual tuple to a dictionary as the dictionarys key.
i want the format to look like this.
dict = {"wealth-gain": value, "gain-burnt": value ......}
how would i create a loop that will go through each tuple in the bigrams list and append it to the dictionary?
Heres what i have
For word in bigrams:
dict[(0+"-"+1) = dict
basicaly i want to take each tuple and add a "-" in between each word in the tuple then append that to a dictionary?
Any ideas how to do this?
Also if the bigram that is going to be appended to the dictionary matches a bigram that is already in the dictionary i would not like to add that bigram to the dictionary. Rather i would like to increment the value of the bigram already in the dictionary.
Any ideas how to do that?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以使用
join
方法:或使用生成器表达初始化:
You can use the
join
method:or express the initialization with a generator:
怎么样:
How about:
您可以直接使用列表中的元组作为字典键——不需要将它们连接到单个字符串。在Python 2.7中,与collections.Counter结合起来特别方便
:
You could use the tuples in the list directly as dictionary keys -- you do not need to join them to a single string. In Python 2.7, this gets particularly convenient in combination with
collections.Counter
:prints
您应该熟悉列表理解。这使得第一个列表的转换变得更容易:
现在看一下 dict 的 setdefault 方法并像这样使用它:
data = {} # dict 是内置的,所以不要将其用作变量名
如果您想要如果是更压缩的版本,您可以查看 itertools 模块。
You should make yourself familiar with list comprehension. That makes the transformation of the first list easier:
Now have a look at the setdefault method of dict and use it like this:
data = {} # dict is build in, so don't use it as variable name
If you want to have an even more compressed version, you might look at the itertools module.
试试这个:
另外,我觉得有必要指出,这些在任何方面、形状或形式上都不是二元组。我不确定你到底想说什么,但它们肯定不是二元组!
try this:
also, I feel obliged to point out that these are not bigrams in any way, shape or form. I'm not sure exactly what you mean to say, but they're certainly not bigrams!