我正在尝试搜索列表的每个元素,以查看该行中是否存在变量customerID
。我有一条语句,将文件customers.txt
的每一行读入一个列表。我使用的方法是使用for循环查看列表的每一行(元素),以查看其中是否存在4数字字符串。无论出于何种原因,该程序似乎只是读取第一行并继续。该问题所附的代码显然效率不高,因为此时我正在尝试使它正常工作的任何方法。
我将客户ID设置为等于1112,因为它位于第一行之后的行中(因此,如果它读取每行,则应该看到它确实存在)
这是一个函数的一部分,它是一个更大的问题的一部分。
代码:
def openAccount():
accountType = str(input("What type of account do you wish to open, checking or savings? "))
#make the user's input lowercase to make checking it simpler
accountType = accountType.lower()
while accountType not in ["checking", "savings"]:
accountType = str(input("Please enter checking or savings, for a checking or savings account: "))
accountType = accountType.lower()
global customerID
customerID = random.randint(1000, 9999)
customerID = 1112
customerID = str(customerID)
global customerlist
with open("customers.txt", "r") as f:
customerlist = [line.strip() for line in f]
# data = [line.strip() for line in open("customers.txt", 'r')]
# for line in data:
# while customerID in line:
# IDExists = True
# if IDExists == True:
# customerID = random.randint(1000, 9999)
# customerID = str(customerID)
# print("Your Customer ID is", customerID)
# else:
# IDExists = False
# print("Your Customer ID is", customerID)
# break
IDExists = False
for line in customerlist:
if customerID in line:
IDExists = True
else:
IDExists = False
if IDExists == True:
customerID = random.randint(1000, 9999)
else:
print("Your customer ID is ", customerID)
customers.txt:
1111 John Doe 11 MyStreet MyCity 12345 NY 23000 200
1112 Kevin Moe 23 HisStreet HerCity 54321 MA 15 3500
1113 Mary Joe 78 SomeStreet NewTown 32451 PA 6500 12000
一旦找到客户ID,您应使用break
停止循环。
for line in customerlist:
if customerID in line:
IDExists = True
break # Stop the loop as soon as we find one, since we initialize IDExists to False, it should remain False if there's nothing found
或者更好的是,使用any(customerID in line for line in customerlist)
。
[无论何时测试成员资格,set
通常都可以很好地完成。您的ID似乎是第一列,因此请将其收集到set
中(不要忘了转换为int
):
def create_customer_set(file):
with open(file) as fh:
customers = set()
# iterate over your file
for line in fh:
# split on spaces, grab the first entry
# and convert to int
cus_id = int(line.split()[0])
customers.add(cus_id)
return customers
customer_ids = create_customer_set('customers.txt')
然后,检查该集中是否有内容是一个恒定时间的操作(不依赖于集中的大小),而且很快。您可以使用generate_customer
方法为您生成新的ID:
def generate_customer(customer_ids):
# your account type code can go here
while True:
customer_id = random.randint(1000, 9999)
# membership test here, continue looping if it's
# in the set
if customer_id in customer_ids:
continue
# otherwise break the loop, you've got a valid customer id
else:
return customer_id
然后您可以对返回的customer_id
执行其他操作>