为什么我不能使用列表对象语法,并且在运行程序时遇到AttributeError:



我为这个问题的长期存在道歉

我想写一段代码,从本质上检查输入的str名称是否已经添加到txt文件中,让我告诉你这个场景:

我使用Classes和Listing来构建我的数据(存储在txt文件中(,以便稍后进行比较,我使用以下代码:

import csv
class Volunteer:
def __init__(self,name,coin_type,weight_of_bag,true_count):
self.name = name
self.coin_type = coin_type        #a function allowing me to class the data
self.weight_of_bag = weight_of_bag
self.TrueCount = true_count
with open("CoinCount.txt","r+") as csvfile:  #opens file as CSV *IMPORTANT*
volunteers = []
for line in csvfile:
volunteers.append(Volunteer(*line.strip().split(',')))

我还创建了一些更简单的代码,比如菜单等,在这个菜单中,尽管我想包括输入新志愿者的能力,但现在我还没有真正进入将新数据添加到txt文件的阶段,然而,我目前正在尝试创建一个检查,检查输入的志愿者姓名是否已经被使用过,只是为了了解更多信息,我将在txt文件中发送数据:

Abena,5p,325.00,Y
Malcolm,1p,3356.00,Y
Jane,£2,120.00,Y
Andy,£1,166.25,N
Sandip,50p,160.00,Y
Liz,20p,250.00,Y
Andy,20p,250.00,Y
Andy,50p,160.00,Y
Jane,£1,183.75,N
Liz,£,179.0,N
Liz,50p,170.0,N
Jane,50p,160.0,Y
Sandip,£1,183.0,N
Jane,£2,132.0,N
Abena,1p,3356.0,N
Andy,2p,250.0,N
Abena,£1,175.0,Y
Malcolm,50p,160.0,Y
Malcolm,£2,175.0,N
Malcolm,£1,175.0,Y
Malcolm,1p,356.0,Y
Liz,20p,250.0,Y
Jane,£2,120.0,Y
Jane,50p,160.0,Y
Andy,£1,175.0,Y
Abena,1p,359.56,N
Andy,5p,328.5,N
Andy,£2,108.0,N
Malcolm,£2,12.0,N

我也会给你这部分菜单的代码,这样如果你想向我解释如何修复它,你就可以使用相同的变量名

def open_menu_1():
inputvolunteername = input("Enter the volunteers name you wish to add: ")
if hasNumbers(inputvolunteername):
yes_or_no = input("volunteer name contains numbers, would you like to try again? ")
if yes_or_no == "yes" or "Yes":
print("")
open_menu_1()
else:
print("")
print("you have been sent back to the main menu")
print("")
open_menu()

elif any(not c.isalnum() for c in inputvolunteername):
yes_or_no = input("volunteer name contains special characters, would you like try again? ")
if yes_or_no == ("yes" or "Yes"):
open_menu_1()
else:
print("")
print("you have been sent back to the main menu")
print("")
elif inputvolunteername == volunteers[0].name:
print("oi")

我设计了一小段代码,如果它能工作,我需要测试它,它显示在上方的代码底部

我基本上运行了程序,并在txt文件(Abena(上键入了第一个名称作为输入,通过这样做,控制台打印出";oi";。我认为这将像代码的这一部分一样困难,因为我认为我现在所要做的就是更换

elif inputvolunteername == volunteers[0].name:
print("oi")

带有

elif inputvolunteername == volunteers[0:].name:
print("oi")

我认为这会起作用,因为在列表中,这通常会从0到无穷大,直到没有其他东西可以从这个名称类类别中搜索,但实际上,一旦我运行该程序,我就会收到以下消息:

elif inputvolunteername==志愿者[0:].name:AttributeError:"list"对象没有属性"name">

这让我很困惑,因为我确实有一个属性"name",这一点很明显,因为我测试的另一行代码确实有效,但只添加了一个冒号,它就表明没有属性

请让我知道我需要更改代码的底线,以使程序检测inputvolunteername是否等于txt文件上已经写入的任何名称。

CSV中存在重复。。。因此,为了测试志愿者名单中的名字,我建议使用set((

inputvolunteername in set([v.name for v in volunteers])

以下返回True

集合中的"Abena"([志愿者中v的v.name](

最新更新