【发布时间】:2021-12-21 09:57:37
【问题描述】:
有没有办法让这段代码更短? 我是一个完整的初学者,我的任务是从账单列表中读出账单数量最多的公司。 我的想法是将每家公司应用到一个列表中,计算该公司出现在该列表中的频率,并将此数量附加到另一个列表中。 然后,我找出账单数量最多的公司的索引,将这些公司附加到一个新列表中,然后从该列表中删除所有重复项,使账单最多的公司只在列表中出现一次。
谢谢!
def company_report(bills):
"""puts every company in list, counts how often each company is in list,
reads the index of company which is the most frequent,
uses index to read out name of company and how many bills it has."""
# append all company names from each bill to list
companies_bills = []
for bill in bills:
# use lower() to make sure that there is no uppercase lowercase error
companies_bills.append(bill[0].lower())
# count how many times each company is in company list
dummy = []
for i in companies_bills:
dummy.append(companies_bills.count(i))
# give out indicis of companies with most occurrences
max_value = max(dummy)
indices = [index for index, value in enumerate(dummy) if value == max_value]
comp = []
# use indicis to append companies with most occurrences to list
for i in indices:
comp.append(companies_bills[i])
# remove duplicates from lists
final_list = []
for company in comp:
if company not in final_list:
final_list.append(company)
row = "| {:17} | {:5} |"
print("\n" + "{:=^29}".format(" Most Popular Company "))
print(row.format("Company", "Bills"))
print(row.format("-" * 17, "-" * 5))
for company in final_list:
print(row.format(company.title(), max(dummy)))
print("=" * 29)
return final_list
【问题讨论】:
-
我不确定,但这可能更适合 Code Review Stack Exchange,但请务必阅读他们的所有规则和他们期望的格式,以防你去那里检查
-
您有几个可以用list comprehensions 定义的列表。我会从那里开始。
-
使用collections.Counter 也可以。
标签: python list loops for-loop max