如何创建一个每次循环并创建一个新列表的输入?
How can I create an input that will loop and create a new list each time?
如果我是 python 的新手还不是很明显,所以如果答案可以像我 5 岁那样解释,那将非常受欢迎。
我基本上是想向自己证明,我可以应用我学到的一些基础知识来制作一个迷你通讯录应用程序。我不希望在应用程序关闭或类似情况后保存数据。只需输入您的姓名、phone 号码和您居住的城市。输入多个姓名后,您可以输入一个特定的姓名,以便将他们的信息打印回给您。
这是我目前拥有的:
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
一个名称,该名称将用于查找列表并打印它。
如何将 Name 的输入分配给 ALSO 当前命名为“User”的内容 list
#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")
为此,您应该使用字典。
每个条目的键应该是与人名对应的字符串 '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
您需要创建一个可以在其中存储多个联系人的变量。每个联系人将是一个列表(或 tuple。这里我使用了一个元组,但无论哪种方式都没有太大关系)。
为此,您可以使用列表的列表,但 dictionary 在这种情况下更合适。
什么是字典?
字典就像一个列表,只是您可以为每个元素命名。此名称称为“键”,最常见的是字符串。这非常适合此用例,因为我们希望能够存储每个联系人的姓名。
字典中的每个值都可以是您想要的任何值 - 在这种情况下,它将存储一个 list/tuple 包含有关用户的信息。
要创建字典,请使用花括号:
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: ")
您应该首先定义 class 以支持名称、phone 和城市。一旦你做到了这一点,其他的就很简单了。
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')
如果我是 python 的新手还不是很明显,所以如果答案可以像我 5 岁那样解释,那将非常受欢迎。
我基本上是想向自己证明,我可以应用我学到的一些基础知识来制作一个迷你通讯录应用程序。我不希望在应用程序关闭或类似情况后保存数据。只需输入您的姓名、phone 号码和您居住的城市。输入多个姓名后,您可以输入一个特定的姓名,以便将他们的信息打印回给您。
这是我目前拥有的:
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
一个名称,该名称将用于查找列表并打印它。
如何将 Name 的输入分配给 ALSO 当前命名为“User”的内容 list
#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")
为此,您应该使用字典。 每个条目的键应该是与人名对应的字符串 '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
您需要创建一个可以在其中存储多个联系人的变量。每个联系人将是一个列表(或 tuple。这里我使用了一个元组,但无论哪种方式都没有太大关系)。
为此,您可以使用列表的列表,但 dictionary 在这种情况下更合适。
什么是字典?
字典就像一个列表,只是您可以为每个元素命名。此名称称为“键”,最常见的是字符串。这非常适合此用例,因为我们希望能够存储每个联系人的姓名。
字典中的每个值都可以是您想要的任何值 - 在这种情况下,它将存储一个 list/tuple 包含有关用户的信息。
要创建字典,请使用花括号:
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: ")
您应该首先定义 class 以支持名称、phone 和城市。一旦你做到了这一点,其他的就很简单了。
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')