我在Python中的新手。我用的字典玩,想知道解决给定的问题
list_ = [['any', 'window', 'says', 'window'], ['dog', 'great'], ['after', 'end', 'explains', 'income', '.', '?']]
dictionary=[('dog', 'cat'), ('window', 'any')]
def replace_matched_items(word_list, dictionary):
int_word = []
int_wordf = []
for lst in word_list:
for ind, item in enumerate(lst):
for key,value in dictionary:
if item in key:
lst[ind] = key
else:
lst[ind] = "NA"
int_word.append(lst)
int_wordf.append(int_word)
return int_wordf
list_ = replace_matched_items(list_, dictionary)
print(list_ )
产生的输出是:
[[['NA', 'window', 'NA', 'window'], ['NA', 'NA'], ['NA', 'NA', 'NA', 'NA', 'NA', 'NA']]]
预期的输出是:
[[['NA', 'window', 'NA', 'window'], ['dog', 'NA'], ['NA', 'NA', 'NA', 'NA', 'NA', 'NA']]]
我使用python提前3个谢谢
一些简要介绍数据结构在Python只是为了澄清你的问题。
my_array = [4, 8, 16, 32]
print(my_array[0]) # returns 4
print(my_array[3]) # returns 32
my_array[2] = 0
print(my_array) # returns [4, 8, 0, 32]
my_tuple = ('this', 'is', 'a', 'tuple', 'of', 'strings')
print(my_tuple[0]) # returns 'this'
my_tuple[1] = 'word' # throws a 'TypeError' as items within tuples cannot be changed.
my_dictionary = {'John':13, 'Bob':31, 'Kelly':24, 'Ryan':17}
print(my_dictionary['Kelly']) # Returns 24
my_dictionary['Kelly'] = 56 # Assigns 56 to Kelly
print(my_dictionary['Kelly']) # Returns 56
的关键是:值取这种形式的字典中,并且每个随后的键 - 值对由逗号分隔。
我会强烈建议阅读对于Python数据结构的官方文档:Link Here
从给定的代码,你使用你的键值对的元组封装在一个列表中的元组作为你的字典数据结构。
你期望的输出是一个结果,你在整个字典迭代,并没有处理,一旦你已经找到了你的字典重点会发生什么。这可以通过一次按键已经发现你的if语句中加入break语句是固定的。 break语句,将退出你的for循环一旦密钥已经发现,将持续到下一个表项。
你的功能最终会看起来像:
def replace_matched_items(word_list, dictionary):
int_word = []
int_wordf = []
for lst in word_list:
for ind, item in enumerate(lst):
for key,value in dictionary:
if item in key:
lst[ind] = key
break
else:
lst[ind] = "NA"
int_word.append(lst)
int_wordf.append(int_word)
return int_wordf
使用您的键和值对的字典数据结构将让你有机会获得这会让你检查是否你的字典里存在的一个关键方法。
如果你有钥匙的列表,你想检查字典键列表中存在:
this_list = ['any', 'window', 'says', 'window', 'dog',
'great', 'after', 'end', 'explains', 'income', '.', '?']
dictionary = {'dog':'cat', 'window':'any'}
matched_list = []
for keys in dictionary:
if keys in this_list:
matched_list.append(keys) # adds keys that are matched
else:
# do something if the key is in not the dictionary
print(matched_list)
# Returns ['dog', 'window']