如何将项目添加到python中的空集 [英] How can I add items to an empty set in python

查看:54
本文介绍了如何将项目添加到python中的空集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下程序:

def myProc(invIndex, keyWord):D={}对于我在范围内(len(keyWord)):如果 invIndex.keys() 中的 keyWord[i]:D.update(invIndex[query[i]])返回 D

但我收到以下错误:

回溯(最近一次调用最后一次):文件<stdin>",第 3 行,在 <module> 中类型错误:无法将字典更新序列元素 #0 转换为序列

如果 D 包含元素,我不会收到任何错误.但我需要 D 一开始为空.

解决方案

D = {} is a dictionary not set.

<预><代码>>>>d = {}>>>类型(d)<输入字典">

使用D = set():

<预><代码>>>>d = 设置()>>>类型(d)<输入'设置'>>>>d.更新({1})>>>d.添加(2)>>>d.更新([3,3,3])>>>d设置([1, 2, 3])

I have the following procedure:

def myProc(invIndex, keyWord):
    D={}
    for i in range(len(keyWord)):
        if keyWord[i] in invIndex.keys():
                    D.update(invIndex[query[i]])
    return D

But I am getting the following error:

Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
TypeError: cannot convert dictionary update sequence element #0 to a sequence

I do not get any error if D contains elements. But I need D to be empty at the beginning.

解决方案

D = {} is a dictionary not set.

>>> d = {}
>>> type(d)
<type 'dict'>

Use D = set():

>>> d = set()
>>> type(d)
<type 'set'>
>>> d.update({1})
>>> d.add(2)
>>> d.update([3,3,3])
>>> d
set([1, 2, 3])

这篇关于如何将项目添加到python中的空集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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