python - 有没有办法可以更紧凑地编写这段代码?
问题描述
有没有办法让这段代码更短?我是一个完整的初学者,我的任务是从账单列表中读出账单数量最多的公司。我的想法是将每家公司都应用到一个列表中,计算该公司出现在该列表中的频率,并将此数量附加到另一个列表中。然后,我找出账单数量最多的公司的索引,将这些公司附加到一个新列表中,然后从该列表中删除所有重复项,以便拥有最多账单的公司只在列表中出现一次。
谢谢你!
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
解决方案
我没有尝试,但它应该工作......
def company_report(bills): """ 将每家公司放入列表中,计算每家公司在列表中的频率,读取最频繁的公司索引,使用索引读取公司名称和它有多少账单。 """
# append all company names from each bill to list
companies_bills = [bill.lower() for bill in bills]
# count how many times each company is in company list
dummy = [companies_bills.count(i) for i in companies_bills]
# give out indicis of companies with most occurrences
max_value = max(dummy)
# use indicis to append companies with most occurrences to list
final_list = list(set([companies_bills[i] for i in [index for index, value in enumerate(dummy) if value == max_value]]))
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_value))
print("=" * 29)
return final_list
推荐阅读
- python - 神经网络如何记住它的训练?
- java - HazelcastSerializationException 将类移动到不同的包后
- database - 从 Clickhouse DB 中完全删除数据以节省磁盘空间
- vhdl - iCE40 Ultra Plus 5k — 如何设置 PLL(无需专有 GUI 工具)(续)
- python - 训练时的良好准确性和损失与验证时的差准确性
- kubernetes - Kubernetes pod 重新调度多次修复 pvc 附件 (GKE)
- python - 创建一个连续计数4行和6行的pandas列计数器
- android - ViewModelTest 中的线程“main @coroutine#2”java.lang.NullPointerException 中的异常?
- autodesk-forge - 通过 Excel 将问题输入回 BIM 360
- amazon-web-services - AWS 许可证管理器:不了解许可证消耗配置中最大生存时间参数的用途