[英]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)):
這是我目前擁有的代碼。 我相信我需要做的事可以通過for循環來完成。 我想做的是循環瀏覽列表,並將每個候選人的投票總數加起來。 當然,如果候選人的姓名匹配,我將需要對其進行正確分配。 如果有人可以,請為我如何以這種方式處理列表指明正確的方向。 多維列表讓我很吃驚。 任何提示或建議都將不勝感激。 謝謝。
因此,您正在尋找的是鍵值結構的數據,例如python字典。 由於這是二維的(候選人名稱和部門名稱),因此需要一個嵌套詞典。
Python不容許autovification如Perl,所以要使用defaultdict自動允許您使用嵌套結構就像一本字典。
這是重構版本:
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))
我拿 有更奇妙的方法,但是可以
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)
或更緊湊
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)
怪異的一線:
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])])
我會用python字典。 根據需要修改您的代碼。
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
您只需要處理代碼當前正在收集的結果。 一種方法是這樣的:
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]))
因此,當有多個候選名稱相同的條目時,您要做的就是遍歷並合並這些條目。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.