【发布时间】:2021-02-01 19:11:08
【问题描述】:
这应该是一个如此简单的问题,但它让我发疯了。当我在字符串列表中搜索关键字'gift'时,只要我手动设置字符串'gift',python就会找到它。当我从字典键派生字符串时,即使字典键是没有拼写错误的相同字符串对象,python 也不会在相关列表中找到它。这是确切的代码:
这个作品:
subtopic_keys = list(copy.deepcopy(subtopic_map).keys())
for element in subtopic_keys:
try:
for dict_object in subtopic_map[element]:
for key2 in dict_object.keys():
for index, entry in enumerate(dict_object[key2]['tweets']):
count = 0
if 'gift' in clean(entry).split():
pass
if 'gift' not in clean(entry).split():
dict_object[key2]['tweets'][index] = 'removed'
except KeyError:
pass
这不起作用。注意:唯一的变化是 'gift' 已被第一个 for 循环中的元素替换,这是一个相同的字符串对象。我通过打印 type(element) 验证了这一点,它属于字符串类。
subtopic_keys = list(copy.deepcopy(subtopic_map).keys())
for element in subtopic_keys:
try:
for dict_object in subtopic_map[element]:
for key2 in dict_object.keys():
for index, entry in enumerate(dict_object[key2]['tweets']):
count = 0
if element in clean(entry).split():
pass
if element not in clean(entry).split():
dict_object[key2]['tweets'][index] = 'removed'
except KeyError:
pass
最后一段代码用 'removed' 替换了每个条目,这意味着 python 不会识别任何条目中的字符串,只要它是从 dict 键派生的。为什么会这样? dict 键是一个相同的字符串类对象。
【问题讨论】:
-
能否包含
subtopic_keys元素。 -
不,这不是确切的代码。它缺少变量。创建minimal reproducible example。
标签: python python-3.x dictionary data-structures types