简体   繁体   中英

Python Two-Dimensional List Processing

loopCount = 0
candidateName = input("Please input the candidates name or type 'DONE' when finished:")
votes = []
while candidateName != "DONE":
     departmentName = input("Please input the department that submitted votes for this candidate:")
     numberOfVotes = input("Please input the number of votes for this candidate:")
     votes.append([])
     votes[loopCount].append(candidateName)
     votes[loopCount].append(departmentName)
     votes[loopCount].append(numberOfVotes)
     print(votes[loopCount])
     loopCount = loopCount + 1
     candidateName = input("Please input the candidates name or type 'DONE' when finished:")

print(votes)

sum = 0
for i in range(0,len(votes)):

This is my code I currently have. I believe what I need done can be done with a for loop. What I'm trying to do is cycle through the list, and add total up each candidate's vote count. Of course, if a candidate has a matching name I would need it to be correctly allocated. If anyone can please just point in the right direction on how I can process a list in this fashion. The multidimensional list is what's throwing me off. Any tips or advice at all would be appreciated. Thank you.

So, what you are looking for is a key,value structure your data such as a python dictionary. Since this is two dimensional (candidate name and department name) you need a nested dictionary.

Python does not allow autovification like perl, so you want to use defaultdict to automatically allow you to use the nested structure like a dictionary.

Here is a refactored version:

from collections import defaultdict
candidates_and_votes = defaultdict(dict)
while True:
     candidateName = input("Please input the candidates name or type 'DONE' when finished:")
     if candidateName == 'DONE':
         break
     departmentName = input("Please input the department that submitted votes for this candidate:")
     numberOfVotes = input("Please input the number of votes for this candidate:")
     candidates_and_votes[candidateName][departmentName] = numberOfVotes

for candidate, department in candidates_and_votes.items():
    total = 0
    print('Candidate Name {}'.format(candidate))
    for dep_name, number in department.items():
        print('  Dep {}. total {}'.format(dep_name, number))
        total += int(number)
    print('     Total Votes = {}'.format(total))

My take. There are fancier ways, but it works

totalvotes = {}
for i in range(0,len(votes)):
     if not votes[i][0] in totalvotes:
          totalvotes[votes[i][0]] = 0
     totalvotes[votes[i][0]] = totalvotes[votes[i][0]]+int(votes[i][2])
print(totalvotes)

or more compact

totalvotes = {}
for vote in votes:
    totalvotes[vote[0]] = totalvotes[vote[0]]+int(vote[2]) if vote[0] in totalvotes else int(vote[2])  
print(totalvotes)

The freaky one-liner:

print([(gk,sum([int(v[2]) for v in gv] )) for gk, gv in itertools.groupby( sorted(votes,key=lambda x:x[0]),lambda x: x[0])])

I would use python dictionary. Modify your code as needed.

votes = [['a','d',3],['b','d',3],['a','d',2]]

unique_names_list = {}
for ballot in votes:
    name = ballot[0]
    department = ballot[1]
    votes = ballot[2]

    name_depart = name + '-' + department

    if name_depart not in unique_names_list.keys():
        unique_names_list[name_depart] = votes
    else:
        unique_names_list[name_depart] = unique_names_list[name_depart] + votes

You would just need to process the results that your code is currently collecting. One way to do that would be like this:

canidates = []
loopCount = 0
candidateName = input("Please input the candidates name or type 'DONE' when finished:")
votes = []
while candidateName != "DONE":
     departmentName = input("Please input the department that submitted votes for this candidate:")
     numberOfVotes = input("Please input the number of votes for this candidate:")
     votes.append([])
     votes[loopCount].append(candidateName)
     votes[loopCount].append(departmentName)
     votes[loopCount].append(numberOfVotes)
     print(votes[loopCount])
     loopCount = loopCount + 1
     candidateName = input("Please input the candidates name or type 'DONE' when finished:")

results = []

#Tally the votes
for v in votes:
    if v[0] in canidates:
        #need to add these votes to an existing canidate.
        for x in results:
            #goes through each record in results and adds the record to it.
            if x[0] == v[0]:
                x[1] = x[1] + ", " + v[1]
                x[2] = x[2] + int(v[2])
    else:
        #need to create a new record for the canidate.
        canidates.append(v[0])
        results.append([v[0],v[1],int(v[2])])


#Display the results
print ("Vote Results:")
for x in results:
    print ("name: " + x[0])
    print ("Departments: " + x[1])
    print ("Votes Total: " + str(x[2]))

So what you would do is go through and combine the entries when there are multiple entries for the same canidate name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM