首页 > 解决方案 > 有没有办法可以更紧凑地编写这段代码?

问题描述

有没有办法让这段代码更短?我是一个完整的初学者,我的任务是从账单列表中读出账单数量最多的公司。我的想法是将每家公司都应用到一个列表中,计算该公司出现在该列表中的频率,并将此数量附加到另一个列表中。然后,我找出账单数量最多的公司的索引,将这些公司附加到一个新列表中,然后从该列表中删除所有重复项,以便拥有最多账单的公司只在列表中出现一次。

谢谢你!

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

标签: pythonlistloopsfor-loopmax

解决方案


我没有尝试,但它应该工作......

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

推荐阅读