Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/280.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python递增列表中的字典值条目_Python_List_Dictionary - Fatal编程技术网

Python递增列表中的字典值条目

Python递增列表中的字典值条目,python,list,dictionary,Python,List,Dictionary,根据前面的一个问题,我在尝试增加列表中包含的字典值时遇到问题,我对使用字典有一些其他想法,但我不确定它们是否可行或可取 我的第一个问题是,如果字典键值包含在列表中,是否可以增加该键值 假设我有一个字典条目 PointsOfInterest = { 'InterestingString1':['String 1 Description', 0], 'InterestingString2':['String 2 Description', 0], 'InterestingString3':['St

根据前面的一个问题,我在尝试增加列表中包含的字典值时遇到问题,我对使用字典有一些其他想法,但我不确定它们是否可行或可取

我的第一个问题是,如果字典键值包含在列表中,是否可以增加该键值

假设我有一个字典条目

PointsOfInterest = {
'InterestingString1':['String 1 Description', 0], 
'InterestingString2':['String 2 Description', 0],
'InterestingString3':['String 3 Description', 0],}
我正在扫描一个文本文件,寻找感兴趣的字符串(在字典中以“键”表示。当发现键匹配时,我希望增加值列表中的计数,在这种情况下,增加上述字典中的第二个列表项。这是否可能实现,因为我当前在运行时会出现打字错误。“字符串1说明”列表项在那里,以便我在运行时可以引用它。)稍后添加到Excel,只是为了将所有内容分组在一起,以便以后更容易扩展脚本,但这似乎会导致我的增量方法出现问题

下面的方法在不使用列表方法的情况下工作,例如,只增加一个值,而不使用“String#Description”条目

for k, v in PointsOfInterest.iteritems():
    if k in mypkt.Text:
        PointsOfInterest[k] = PointsOfInterest[k] + 1
我还有一个类似于上面的问题,但是我不希望增加一个值,而是希望将该值附加到dict中的列表中!我怀疑这可能太多了,但是按照下面的dict

ValuesOfInterest = {
'AnotherString1':['Short Description1', []], 
'AnotherString2':['Short Description2', []],
'AnotherString3':['Short Description3', []],}

您还需要索引到列表对象中:

for k, v in PointsOfInterest.iteritems():
    if k in mypkt.Text:
        PointsOfInterest[k][1] = PointsOfInterest[k][1] + 1
或更短(因为已经有
v
引用相同的值):

这同样适用于将项目附加到值中的嵌套列表:

for k, v in PointsOfInterest.iteritems():
    if k in mypkt.Text:
        v[1].append(mykt.Text)

增加计数器的问题在于这一行:

PointsOfInterest[k] = PointsOfInterest[k] + 1
您正试图将
1
添加到列表中,而不是项目中。您可以通过添加要添加到的列表元素来更正此问题:

PointsOfInterest[k][1] = PointsOfInterest[k][1] + 1
您的追加问题可能与此问题相同。您需要追加到子列表中的元素:

ValuesOfInterest[k][1].append(NEWITEM)

谢谢@Martijn Pieters我就快到了,但我是按照[k][v[1]]+1的思路来做的。再次感谢你的帮助谢谢Andy,我想在我的列表中写得太详细了。
ValuesOfInterest[k][1].append(NEWITEM)