如何将元素添加到已经存在的元素而不是在列表中覆盖它们?

How to add elements to the already existing elements instead of overwriting them in a list?

我这里有这段代码:

def alist():
    wor = []
    definition = []
    wele = str(input("Enter a word: "))
    dele = str(input("Enter a definition: "))
    x = wor.append(wele)
    y = def.append(dele)
    print("Words' List: ", wor, "\nDefinitions' List: ", definition)

每当我 运行 它时,我可以将元素添加到列表 wordef,但是,每当我再次 运行 它时,它会覆盖我的元素在我第一次 运行 时添加。我通过将 wordef 变成全局变量来避免这个问题。除了把这两个列表做成全局变量还有什么办法吗?

谢谢!

当你追加到你的列表时,你将它分配给新变量,x 和 y,但你永远不会对它们做任何事情。 wordef 永远不会改变。您实际上不必将 append() 分配给新变量,它会发生 in-place.

如果你希望你的两个列表在每次调用函数时始终保留它们包含的内容,那么你应该在函数范围之外定义它们,否则每次调用函数时你 re-initiate 它们作为空列表。

l1 = []
l2 = []

def alist():
     wele = str(input("Enter a word: "))
     dele = str(input("Enter a definition: "))
     l1.appnd(wele)
     l2.append(dele)
     print("Words' List: ", l1, "\nDefinitions' List: ", l2)

您每次调用函数时都会创建新的空列表。该函数应将列表作为参数并对其进行修改。

def alist(wlist, dlist):
    wele = input("Enter a word: ")
    dele = input("Enter a definition: ")
    wlist.append(wele)
    dlist.append(dele)

word_list = []
def_list = []

word_count = int(input("How many words are you defining? "))
for _ in range(word_count):
    alist(word_list, def_list)
print("Words' List: ", word_list, "\nDefinitions' List: ", def_list)

制作列表参数允许您有多个单词列表,例如

spanish_words = []
spanish_defs = []
alist(spanish_words, spanish_defs)

但是,将相关数据保存在单独的列表中通常是糟糕的设计,您必须保持同步。最好使用单个字典或元组列表,这样所有相关项(例如单词及其定义)都在一起。