有沒有辦法讓這段代碼更短?我是一個完整的初學者,我的任務是從賬單清單中讀出賬單數量最多的公司。我的想法是將每個公司都應用到一個串列中,計算該公司出現在該串列中的頻率,并將這個數量附加到另一個串列中。然后,我找出賬單金額最多的公司的索引,將這些公司附加到一個新串列中,然后從該串列中洗掉任何重復項,以便賬單最多的公司在串列中只出現一次。
謝謝你!
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
uj5u.com熱心網友回復:
我還沒有嘗試過,但它應該可以作業...
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/352898.html
上一篇:Preact構建尺寸太大
