Python 该问题要求对照字典检查列表,并在列表中未出现在字典中的项目之前添加*号
我想为列表中未在字典中找到的每个项目添加(*)。 以下是我目前拥有的:Python 该问题要求对照字典检查列表,并在列表中未出现在字典中的项目之前添加*号,python,python-3.x,dictionary,Python,Python 3.x,Dictionary,我想为列表中未在字典中找到的每个项目添加(*)。 以下是我目前拥有的: dictionary = {'a', 'b', 'd'} words = ['d', 'c', 'x', 'a'] for i in words: if i not in dictionary: words[i] = '*' + words[i] 我得到一个错误: TypeError:列表索引必须是整数或片,而不是str 据我所知,这意味着它不能通过for循环,因为它不是数字,但我不知道如何修复它。
dictionary = {'a', 'b', 'd'}
words = ['d', 'c', 'x', 'a']
for i in words:
if i not in dictionary:
words[i] = '*' + words[i]
我得到一个错误:
TypeError:列表索引必须是整数或片,而不是str
据我所知,这意味着它不能通过for循环,因为它不是数字,但我不知道如何修复它。我甚至不知道该查什么:(
我是python新手,所以请温柔些。首先,您的
字典
变量实际上是一个集
,其次,您可以使用范围
和len
循环索引而不是值:
dictionary = {'a', 'b', 'd'} # actually a set
words = ['d', 'c', 'x', 'a']
for i in range(len(words)):
if words[i] not in dictionary:
words[i] = '*' + words[i]
print(words)
输出:
['d', '*c', '*x', 'a']
或者,您可以使用枚举
,这将为您提供索引和值,而无需手动索引列表
,即可获得值:
for i, word in enumerate(words):
if word not in dictionary:
words[i] = '*' + word
在Python中获得所需结果的自然方法是使用所需的值创建一个新的列表,这可以通过列表理解轻松实现
to_mark = {'a', 'b', 'd'} # mark words that are in this set.
words = ['d', 'c', 'x', 'a']
words = ['*' + w if w in to_mark else w for w in words]
这里介绍了两个概念:列表理解,它允许我们根据现有列表来描述一个列表,以及条件表达式(
'*'+w,如果w in to_mark else w
)当w
是in to_mark
时,我们生成'*'+w
;否则
我们生成原始的w
一个不需要直接索引的替代方法是直接用列表理解替换单词
列表,如下所示
dictionary = {'a', 'b', 'd'} # actually a set
words = ['d', 'c', 'x', 'a']
words = [w if w in dictionary else '*'+w for w in words]
print(words)
有输出
['d', '*c', '*x', 'a']
这是推荐的方法,但在一个明显的家庭作业问题上,这真的太过分了