简体   繁体   English

Python二维列表处理

[英]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. 我相信我需要做的事可以通过for循环来完成。 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. 因此,您正在寻找的是键值结构的数据,例如python字典。 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. Python不容许autovification如Perl,所以要使用defaultdict自动允许您使用嵌套结构就像一本字典。

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. 我会用python字典。 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. 因此,当有多个候选名称相同的条目时,您要做的就是遍历并合并这些条目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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