如何更换从给定的字典中的项目?

问题描述 投票:1回答:1

我在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-3.x dictionary
1个回答
0
投票

一些简要介绍数据结构在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']
© www.soinside.com 2019 - 2024. All rights reserved.