以防我對 python 不熟悉,所以如果答案可以像我 5 歲那樣解釋,那將是非常受歡迎的。
我基本上是想向自己證明,我可以將學到的一些基礎知識應用到制作迷你通訊錄應用程式中。我不希望在應用程式關閉或類似情況后保存資料。只需輸入您的姓名、電話號碼和您居住的城市。輸入多個姓名后,您可以輸入特定姓名,將其資訊列印回給您。
這是我到目前為止所擁有的:
Name = input("enter name here: ")
Number = input("enter phone number here: ")
City = input("enter city here: ")
User = list((Name, Number, City))
這對于為 python 提供資料的作業效果很好。我做了另一個輸入,讓 python 將資訊列印回給我,只是為了確保 python 正在做我想做的事情:
print("Thank you! \nWould you like me to read your details back to you?")
bck = input("Y / N")
if bck == "Y":
print(User)
print("Thank you! Goodbye")
else:
print("Goodbye!")
其輸出是用戶通過三個輸入創建的串列。太棒了!我很高興到目前為止我已經設法讓它發揮作用。
但我希望 'Name'input成為 'User' 的名稱list。這樣,如果我向用戶詢問input一個名稱,該名稱將用于查找串列并列印它。如何將名稱中的輸入分配給當前命名為“用戶”的內容list
uj5u.com熱心網友回復:
您將需要創建一個可以在其中存盤多個聯系人的變數。每個聯系人將是一個串列(或一個元組。這里我使用了一個元組,但無論哪種方式都無關緊要)。
為此,您可以使用串列串列,但在這種情況下字典會更合適。
什么是字典?
字典就像一個串列,只是你可以給每個元素一個名字。此名稱稱為“鍵”,通常是字串。這非常適合這個用例,因為我們希望能夠存盤每個聯系人的姓名。
字典中的每個值都可以是您想要的任何值 - 在這種情況下,它將存盤一個包含用戶資訊的串列/元組。
要創建字典,請使用大括號:
empty_dictionary = {}
dictionary_with_stuff_in_it = {
"key1": "value1",
"key2": "value2"
}
要從字典中獲取專案,請使用方括號對其進行索引,并在方括號內放置一個鍵:
print(dictionary_with_stuff_in_it["key1"]) # Prints "value1"
您還可以像這樣設定一個專案/將一個新專案添加到字典中:
empty_dictionary["a"] = 1
print(empty_dictionary["a"]) # Prints 1
如何在這里使用字典
在代碼開始時,您應該創建一個空字典,然后在收到輸入時,您應該添加到字典中。
這是我制作的代碼,其中我使用了一個 while 回圈來繼續接收輸入,直到用戶想要退出:
contacts = {}
msg = "Would you like to: \n - n: Enter a new contact \n - g: Get details for an existing contact \n - e: Exit \nPlease type n, g, or e: \n"
action = input(msg)
while action != "e":
if action == "n": # Enter a new contact
name = input("Enter name here: ")
number = input("Enter phone number here: ")
city = input("Enter city here: ")
contacts[name] = (number, city)
print("Contact saved! \n")
action = input(msg)
elif action == "g": # Get details for an existing contact
name = input("Enter name here: ")
try:
number, city = contacts[name] # Get that contact's information from the dictionary, and store it into the number and city variables
print("Number:", number)
print("City:", city)
print()
except KeyError: # If the contact does not exist, a KeyError will be raised
print("Could not find a contact with that name. \n")
action = input(msg)
else:
action = input("Oops, you did not enter a valid action. Please type n, g, or e: ")
uj5u.com熱心網友回復:
#can be easier to use with a dictionary
#but its just basic
#main list storing all the contacts
Contact=[]
#takes length of contact list,'int' just change input from string to integer
contact_lenght=int(input('enter lenght for contact'))
print("enter contacts:-")
#using for loop to add contacts
for i in range(0,len(contact_lenght)):
#contact no.
print("contact",i 1)
Name=input('enter name:')
Number=input('enter number:')
City=input("enter city:")
#adding contact to contact list using .append(obj)
Contact.append((Name,Number,City))
#we can directly take input from user using input()
bck=input("Thank you! \nWould you like me to read your details back to you?[y/n]:")
#checking if user wants to read back
if bck=='y':
u=input("enter your name:")
#using for loop to read contacts
for i in range(0,len(Contact)):
#if user name is same as contact name then print contact details
if u==Contact[i][0]:
print("your number is",Contact[i][1])
print("your city is",Contact[i][2])
else:
#if user doesnt want to read back then print thank you
print("Good bye")
uj5u.com熱心網友回復:
為此,您應該使用字典。每個條目的鍵應該是與人名對應的字串“User[0]”。每個條目的內容應該是包含該用戶資訊的串列。
我給你舉個例子:
# first we need to create an empty dictionary
data = {}
# in your code when you want to store information into
# the dictionary you should do like this
user_name = User[0] # this is a string
data[user_name] = User # the list with the information
如果你想訪問一個人的資訊,你應該這樣做:
# user_you_want string with user name you want the information
data[user_you_want]
您也可以使用以下命令洗掉資訊:
del data[user_you_want_to_delete]
您可以在此處獲取有關字典的更多資訊:https ://docs.python.org/3/tutorial/datastructures.html#dictionaries
uj5u.com熱心網友回復:
您應該首先定義一個類來支持姓名、電話和城市。一旦你做到了,其他一切都很容易。
class Data:
def __init__(self, name, city, phone):
self.name = name
self.city = city
self.phone = phone
def __eq__(self, other):
if isinstance(other, str):
return self.name == other
if isinstance(name, type(self)):
return self.name == other.name and self.city == other.city and self.phone == other.phone
return False
def __str__(self):
return f'Name={self.name}, City={self.city}, Phone={self.phone}'
DataList = []
while (name := input('Name (return to finish): ')):
city = input('City: ')
phone = input('Phone: ')
DataList.append(Data(name, city, phone))
while (name := input('Enter name to search (return to finish): ')):
try:
print(DataList[DataList.index(name)])
except ValueError:
print('Not found')
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/479556.html
標籤:Python python-3.x 列表 输入
上一篇:最大功能似乎無法正常作業?
