我正试图编写一种算法,它可以"自动"添加值。当用户输入新东西时,返回到字典。例如…
my_friends = {}
friends = input("What is your friend name?")
#when i type the name, programm should add it itself. Thanks for advices.
friends = {}
def addFriend():
friends.update({input("What is your friend name?"): None})
addFriend() # asks for the friend...
addFriend() # asks for another friend...
print(friends)
这是一个使用函数的例子,在我们的例子中,它被命名为addFriend
。该函数基本上只是使用字典update
的内置方法更新friends
字典。update
获取另一个字典,并使用该字典修改当前字典friends
的内容。
假设你在输入中输入了Jessica
,它将被存储在friends
字典中作为{"Jessica": None}
。稍后,您可以通过在字典上执行dict[key]
表示法来访问这个添加的键、值对。因此,friends["Jessica"]
将等于None
,因为在函数中,我们只是将输入字符串添加为键,并将None
作为该键的默认值。
希望对你有帮助。
您错过了字典的要点:使用字典必须指定键,例如,您可以使用字典来表示您的"朋友":
friend = {
'first_name': 'John',
'last_name': 'Smith',
}
在您的情况下,您想要使用一个列表,使用[]
而不是{}
创建,然后将输入值附加到您的列表:
my_friends = []
my_friends.append(input("What is your friend name?"))
要在list
中添加单个元素,可以使用append()
方法。
如果你想用一种更通用的方式来做事情,就像你要求的algorithm which it can add value "automatically"
一样,下面是一个解决方案,当然更复杂,但也更通用:
此外,由于您似乎没有使用密钥,因此这是基于list
的解决方案:
#You define a function you can use anywhere in your code after
#The function takes the list lst and the string name as inputs
def add_name(lst,name):
#Here is the append() part. By doing as below, you append name to the end of lst
lst.append(name)
#You return your modified list lst
return lst
#Your empty list of friends
my_friends = []
#Get the friends name from input()
friends = input("What is your friend name?")
#Say your my_friends list is equal to what add_name function returns
my_friends = add_name(my_friends,friends)
#Print
print (my_friends)
输出:#The add_name function did append the name of your friend to the empty list
['john']
如果你想添加多个好友:
def add_name(lst,name):
lst.append(name)
return lst
my_friends = []
#Ask for how many friends you want to add
#Input in always a string so we convert to int for needs below
number = int(input("How many?"))
#You use a for loop with number of iterations equal to number (the How many?)
for i in range(number):
friends = input("What is your friend name?")
#A new name will be appended each iteration through your function
my_friends = add_name(my_friends,friends)
print (my_friends)
关于基础知识的实践培训,我建议:
https://www.w3schools.com/python/ref_list_append.asphttps://www.w3schools.com/python/python_for_loops.asphttps://www.w3schools.com/python/python_functions.asp
my_friends = {}
my_friends["name"] = str(input("What is your friend's name?"))