Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/303.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何修改列表中对象内的元素?_Python - Fatal编程技术网

Python 如何修改列表中对象内的元素?

Python 如何修改列表中对象内的元素?,python,Python,我相信这是一个非常简单的问题,但我很难修改对象列表中单个对象中的元素。我有一个名为“志愿者设置”的对象: #Create the volunteer class class Volunteer(): consecutiveDaysOff = 0 totalDaysOff = 0 locWorked = [] schedule = [] def __init__(self, employeeId): self.employeeId = em

我相信这是一个非常简单的问题,但我很难修改对象列表中单个对象中的元素。我有一个名为“志愿者设置”的对象:

#Create the volunteer class
class Volunteer():
    consecutiveDaysOff = 0
    totalDaysOff = 0
    locWorked = []
    schedule = []

    def __init__(self, employeeId):
        self.employeeId = employeeId

    def updateSchedule(self,location):
        self.schedule.append(location)

    def newDayOff(self):
        self.totalDaysOff =+1
        self.consecutiveDaysOff =+ 1
        self.schedule.insert(0,0)
我有一份志愿者名单:

v1 = Volunteer(1)
v2 = Volunteer(2)
v3 = Volunteer(3)
volunteerList = [v1,v2,v3]
我想使用以下命令在列表的一个元素上运行newDayOff():志愿者列表[0]。newDayOff()

但每次我这样做时,它都会对列表中的每个志愿者实例运行newdayoff()。正确的方法是什么

import csv

#Create the volunteer class
class Volunteer():
    consecutiveDaysOff = 0
    totalDaysOff = 0
    locWorked = []
    schedule = []

    def __init__(self, employeeId):
        self.employeeId = employeeId

    def updateSchedule(self,location):
        self.schedule.append(location)

    def newDayOff(self):
        self.totalDaysOff =+1
        self.consecutiveDaysOff =+ 1
        self.schedule.insert(0,0)


# Test Variables
v1 = Volunteer(1)
v2 = Volunteer(2)
v3 = Volunteer(3)
v2.consecutiveDaysOff = 1
v1.totalDaysOff = 1
v2.totalDaysOff = 3
v3.totalDaysOff = 4

numVolunteers = 3
location = [1]
numLocation = 1


volunteerList = [v1,v2,v3]

#test inputs


#Take inputs

# try:
#     days = int(input("How many days are in the month? ") )
# except ValueError:
#     print("Invalid Input... Please Restart Program")
#     exit()
#
# try:
#     numVolunteers = input("How many volunteers are there? ")
# except ValueError:
#     print("Invalid Input... Please Restart Program")
#     exit()

# try:
#     location = input("What are the locations? (Should be numbers separated by ',')")
#
#     if location == "":
#         print("Locations were not entered.")
#         exit()
#
#     numLocation = 1
#     for i in range(0,len(location)):
#         if location[i] == ',':
#             numLocation = numLocation + 1
#
#     location = location.replace(" ", "")
#     location = location.split(',')
#     location = list(map(int, location))
#
# except ValueError:
#     print("Invalid Input... Please Restart Program")
#     exit()

#create the volunteer list
def createVolunteerList():
    for i in range(0,numVolunteers):
        volunteerList.append(Volunteer(i))

def sortArrayByConsecDaysOff():
    for i in range(0,len(volunteerList)):
        for j in range(0,len(volunteerList)):
            if volunteerList[i].consecutiveDaysOff > volunteerList[j].consecutiveDaysOff:
                volunteerList[i],volunteerList[j] = volunteerList[j],volunteerList[i]

def sortArrayByTotalDaysOff():
    for i in range(0,len(volunteerList)):
        for j in range(0,len(volunteerList)):
            if volunteerList[i].totalDaysOff < volunteerList[j].totalDaysOff:
                volunteerList[i], volunteerList[j] = volunteerList[j], volunteerList[i]

def printVolunteer():
    for i in range(0,len(volunteerList)):
        v = volunteerList[i]
        print(v.employeeId, " " ,v.consecutiveDaysOff, " " ,v.totalDaysOff, " " , v.locWorked, " ", v.schedule, "\n")

def assignDaysOff():
    # Define number of days off that can be taken that day
    remainingDaysOff = numVolunteers - numLocation


    # Loop through volunteers to give weekends to those that have had one consecutive day off.
    for i in range(0, len(volunteerList)):
        if volunteerList[i].consecutiveDaysOff == 1 and remainingDaysOff > 0:
            volunteerList[i].newDayOff()
            remainingDaysOff = remainingDaysOff - 1


    sortArrayByTotalDaysOff()
    # Loop through volunteers to assign weekends to those with the fewest days off so far.
    for i in range(0, len(volunteerList)):
        if remainingDaysOff > 0 and not volunteerList[i]:
            volunteerList[i].newDayOff()
            remainingDaysOff = remainingDaysOff - 1

printVolunteer()
volunteerList[0].newDayOff()
printVolunteer()
导入csv
#创建志愿者课程
类志愿者():
连续日期f=0
totalDaysOff=0
locWorked=[]
附表=[]
定义初始(自我,员工ID):
self.employeeId=employeeId
def更新计划(自身、位置):
self.schedule.append(位置)
def newDayOff(自我):
self.totalDaysOff=+1
self.continuedAysoff=+1
自我计划。插入(0,0)
#测试变量
v1=志愿者(1)
v2=志愿者(2)
v3=志愿者(3)
v2.continuousedaysoff=1
v1.TotalDaysof=1
v2.TotalDaysof=3
v3.TotalDaysof=4
numvolunters=3
位置=[1]
数值位置=1
志愿者列表=[v1、v2、v3]
#测试输入
#听取意见
#尝试:
#days=int(输入(“一个月有多少天?”)
#除值错误外:
#打印(“无效输入…请重新启动程序”)
#退出()
#
#尝试:
#NUMVolunters=输入(“有多少志愿者?”)
#除值错误外:
#打印(“无效输入…请重新启动程序”)
#退出()
#尝试:
#位置=输入(“位置是什么?(应该是以“,”分隔的数字”)
#
#如果位置==“”:
#打印(“未输入位置”)
#退出()
#
#数值位置=1
#对于范围(0,len(位置))中的i:
#如果位置[i]==',':
#numLocation=numLocation+1
#
#位置=位置。替换(“,”)
#location=location.split(',')
#位置=列表(地图(内部,位置))
#
#除值错误外:
#打印(“无效输入…请重新启动程序”)
#退出()
#创建志愿者名单
def CreateList():
对于范围内的i(0,numvolunters):
志愿者名单。附加(志愿者(一))
def SORTARRAYBY CONSECTIONDAYSOFF():
对于范围(0,len(列表))中的i:
对于范围(0,len(列表))内的j:
如果志愿者列表[i]。连续日期>志愿者列表[j]。连续日期:
志愿者名单[i],志愿者名单[j]=志愿者名单[j],志愿者名单[i]
def sortArrayByTotalDaysOff():
对于范围(0,len(列表))中的i:
对于范围(0,len(列表))内的j:
如果志愿者列表[i].totalDaysOff<志愿者列表[j].totalDaysOff:
志愿者名单[i],志愿者名单[j]=志愿者名单[j],志愿者名单[i]
def PRINTOPTIONAL():
对于范围(0,len(列表))中的i:
v=志愿者名单[i]
打印(v.employeeId,“,v.ConcertiveDaysoff,”,v.totalDaysOff,“,v.Locaworked,”,v.schedule,“\n”)
def assignDaysOff():
#定义当天可以休假的天数
剩余天数f=numvolunters-numLocation
#通过志愿者循环,给那些连续休息一天的人安排周末。
对于范围(0,len(列表))中的i:
如果志愿者列表[i]。ConcertiveDaysOff==1,剩余天数Off>0:
志愿者名单[i].newDayOff()
remainingDaysOff=remainingDaysOff-1
SortarayByTotalDaysoff()
#通过志愿者循环,将周末分配给迄今为止休假天数最少的人。
对于范围(0,len(列表))中的i:
如果remainingDaysOff>0而不是志愿者列表[i]:
志愿者名单[i].newDayOff()
remainingDaysOff=remainingDaysOff-1
打印志愿者()
志愿者列表[0]。newDayOff()
打印志愿者()
更改此选项

> class Volunteer():
>     consecutiveDaysOff = 0
>     totalDaysOff = 0
>     locWorked = []
>     schedule = []
> 
>     def newDayOff(self):
>         self.totalDaysOff =+1
>         self.consecutiveDaysOff =+ 1
>         self.schedule.insert(0,0)

这应该可以解决问题。

更改此选项:

class Volunteer():
    consecutiveDaysOff = 0
    totalDaysOff = 0
    locWorked = []
    schedule = []
为此:

class Volunteer():
    consecutiveDaysOff = 0
    totalDaysOff = 0
    def __init__(self):
        self.locWorked = list()
        self.schedule = list()

您的代码在志愿者对象的每个实例中都使用相同的列表实例。

除非您在某个我看不到的地方有共享状态,否则我看不到导致该行为的代码。由于您没有指定带参数的构造函数,此代码似乎完全失败。这段代码不会运行,所以我不确定您是如何测试它的。看起来问题可能出在您的属性实例化上。尝试在类的
\uuuuu init\uuuu
方法中设置属性。我复制/粘贴了迄今为止我编写的全部代码和我正在使用的测试用例。上次我检查时,上的可执行代码片段不适用于仅python的javascript。这并没有修复它。
class Volunteer():
    consecutiveDaysOff = 0
    totalDaysOff = 0
    def __init__(self):
        self.locWorked = list()
        self.schedule = list()