我有下一個代碼,我為每個入口寵物創建物件:
from itertools import groupby
class Petshop():
def __init__(self, entryDate, name, ownerName):
self.entryDate = entryDate
self.name = name
self.ownerName = ownerName
class Pets():
def __init__(self):
self.petsList = []
def addPets(self, entryDate, name, ownerName):
entry_pet = Petshop(entryDate, name, ownerName)
self.petsList.append(entry_pet)
def printPets(self):
self.petsList.sort(key=lambda p: p.entryDate)
counter = 0
for group in groupby(self.petsList, key=lambda p: p.entryDate):
ls = list(group)
print("---------------", ls[0], '------------------')
for pet in list(ls[1]):
print("Name:", pet.name)
print("Owner name:", pet.ownerName)
if pet.name in list(ls[1]):
counter = 1
print('There are ',counter,'pets with the same name')
pet = Pets()
pet.addPets('04/13/2021','Pinky', 'David Smith')
pet.addPets('07/10/2020', 'Charlie', 'Joe Davis')
pet.addPets('04/13/2021','Pinky', 'Daniel Trincot')
pet.addPets('07/10/2020', 'Kenny', 'Susan Jones')
pet.addPets('12/22/2018', 'Teddy', 'Carl Johnson')
pet.addPets('07/10/2020', 'Kenny', 'Richard Campbell')
pet.addPets('04/13/2021','Max', 'Bryan Miller')
pet.addPets('07/10/2020', 'Buddy', 'Kathy Brown')
pet.addPets('07/10/2020', 'Kenny', 'John Brown')
pet.printPets()
使用該代碼,我想按日期計算有多少重復的寵物條目,例如我希望在控制臺中:
--------------- 04/13/2021 ------------------
Name: Pinky
Owner name: David Smith
Name: Pinky
Owner name: Daniel Trincot
Name: Max
Owner name: Bryan Miller
There are 2 pets with the same name
--------------- 07/10/2020 ------------------
Name: Charlie
Owner name: Joe Davis
Name: Kenny
Owner name: Susan Jones
Name: Kenny
Owner name: Richard Campbell
Name: Buddy
Owner name: Kathy Brown
Name: Kenny
Owner name: John Brown
There are 3 pets with the same name
--------------- 12/22/2018 ------------------
Name: Teddy
Owner name: Carl Johnson
There are 0 pets with the same name
我試圖這樣做:
if pet.name in list(ls[1]):
counter = 1
但這不起作用,因為我認為我的代碼沒有進入 if 而我只是進入控制臺:
--------------- 04/13/2021 ------------------
Name: Pinky
Owner name: David Smith
There are 0 pets with the same name
Name: Pinky
Owner name: Daniel Trincot
There are 0 pets with the same name
Name: Max
Owner name: Bryan Miller
There are 0 pets with the same name
--------------- 07/10/2020 ------------------
Name: Charlie
Owner name: Joe Davis
There are 0 pets with the same name
Name: Kenny
Owner name: Susan Jones
There are 0 pets with the same name
Name: Kenny
Owner name: Richard Campbell
There are 0 pets with the same name
Name: Buddy
Owner name: Kathy Brown
There are 0 pets with the same name
Name: Kenny
Owner name: John Brown
There are 0 pets with the same name
--------------- 12/22/2018 ------------------
Name: Teddy
Owner name: Carl Johnson
There are 0 pets with the same name
所以我來這里尋求幫助。
uj5u.com熱心網友回復:
對printPets方法的更改(針對 PEP 8 進行了調整,但仍應清楚每個名稱所指的內容)(以下完整代碼示例中有更詳細的說明):
from collections import Counter
...
def print_all_pets(self):
for date, group in groupby(sorted(self.pets_list, key=lambda x: x.entry_date),
key=lambda x: x.entry_date):
print(f'{"-" * 20} {date} {"-" * 20}')
counter = Counter()
for pet in group:
print(f"Name: {pet.name}")
print(f"Owner name: {pet.owner_name}")
counter[pet.name] = 1
print(f'There are {max(counter.values())} '
f'pets with the same name')
完整的代碼示例(它也遵循 PEP 8,我建議你也遵循);大部分解釋都在代碼注釋中:
from itertools import groupby
from dataclasses import dataclass, field
from collections import Counter
# using dataclasses because they make it easier
# to create more data driven objects and they can pre-build
# all the comparison methods so that sorting is way easier
# and you can exclude what not to sort
@dataclass(order=True)
class PetShop:
entry_date: str
name: field(default_factory=str, compare=False)
owner_name: field(default_factory=str, compare=False)
class Pets:
def __init__(self):
self.pets_list = []
def add_pet(self, entry_date, name, owner_name):
entry_pet = PetShop(entry_date, name, owner_name)
self.pets_list.append(entry_pet)
def print_all_pets(self):
# as you can see no key is needed for sorting the `PetShop` instances
# because dataclass allows to do so, then just group them by their date
# which seems to require some function, also unpack both values:
# the date and the group
for date, group in groupby(sorted(self.pets_list), key=lambda x: x.entry_date):
# use f-string for formatting and also you can multiply strings
print(f'{"-" * 20} {date} {"-" * 20}')
# use counter for counting and update it with the pet name
# each iteration
counter = Counter()
for pet in group:
print(f"Name: {pet.name}")
print(f"Owner name: {pet.owner_name}")
# update the counter
counter[pet.name] = 1
# then get the highest count
print(f'There are {max(counter.values())} '
f'pets with the same name')
pets = Pets()
# use a list to make the code less repetitive, this
# allows to loop over the list and add each item to the
# pets.pets_list less repetitively than calling the `add_pet`
# method multiple times manually
pet_shops = [
('04/13/2021', 'Pinky', 'David Smith'),
('07/10/2020', 'Charlie', 'Joe Davis'),
('04/13/2021', 'Pinky', 'Daniel Trincot'),
('07/10/2020', 'Kenny', 'Susan Jones'),
('12/22/2018', 'Teddy', 'Carl Johnson'),
('07/10/2020', 'Kenny', 'Richard Campbell'),
('04/13/2021', 'Max', 'Bryan Miller'),
('07/10/2020', 'Buddy', 'Kathy Brown'),
('07/10/2020', 'Kenny', 'John Brown')
]
for e_date, p_name, o_name in pet_shops:
pets.add_pet(e_date, p_name, o_name)
pets.print_all_pets()
你最初的問題是你檢查了一個字串是否在一個PetShop實體串列中,所以它總是會評估為False(即使正確使用條件(例如,實際上檢查寵物名稱是否在寵物名稱串列中),它只會給出每個分組的寵物總數)。因此,對于如上所示的計數,我建議使用,collections.Counter因為它比手動制作演算法要容易得多。
有用的來源:
dataclasses圖書館(內置)collections.Counter檔案(內置)itertools.groupby檔案(更多示例)
關于 PEP 8:
我強烈建議遵循PEP 8 - Python 代碼風格指南。函式名和變數名應該在snake_case,類名應該在CapitalCase. 沒有足夠的空間周圍=,如果它被用作關鍵字引數的一部分,( func(arg='value')),但周圍有空間,=如果是用于分配的值(variable = 'some value')。在運算子周圍留出空間( -/等value = x y:(此處除外value = x y))。在函式和類宣告周圍有兩個空行。類方法周圍有一個空行。
uj5u.com熱心網友回復:
首先使用 entryDate 然后按名稱分組
for i, j in groupby(pet.petsList, key=lambda p: p.entryDate):
print(f"-------{i}-----------")
for item1, item2 in groupby(list(j), key=lambda k: k.name):
dic = {}
for k1 in list(item2):
if k1.name in dic:
dic[k1.name] = dic[k1.name] 1
else:
dic[k1.name] = 1
print(f"Name: {k1.name}")
print(f"Owner name: {k1.ownerName}")
print(dic)
它產生以下結果
-------04/13/2021-----------
Name: Pinky
Owner name: David Smith
Name: Pinky
Owner name: Daniel Trincot
{'Pinky': 2}
Name: Max
Owner name: Bryan Miller
{'Max': 1}
-------07/10/2020-----------
Name: Charlie
Owner name: Joe Davis
{'Charlie': 1}
Name: Kenny
Owner name: Susan Jones
Name: Kenny
Owner name: Richard Campbell
{'Kenny': 2}
Name: Buddy
Owner name: Kathy Brown
{'Buddy': 1}
Name: Kenny
Owner name: John Brown
{'Kenny': 1}
-------12/22/2018-----------
Name: Teddy
Owner name: Carl Johnson
{'Teddy': 1}
uj5u.com熱心網友回復:
我可以在上面的代碼中看到三個問題。
- groupby 創建了一個生成器,它只會有一次可迭代的資料。
def printPets(self):
self.petsList.sort(key=lambda p: p.entryDate)
counter = 0
for group in groupby(self.petsList, key=lambda p: p.entryDate):
ls = list(group)
print(f'first {list(ls[1])}')
print(f'second {list(ls[1])}')
#first [<__main__.Petshop object at 0x7fcd1001e430>, <__main__.Petshop object at 0x7fcd504428b0>, <__main__.Petshop object at 0x7fcd50446d00>]
#second []
您嘗試在組上使用 list() 是正確的,但您需要先解壓日期和寵物。這是一個可能的修復
def printPets(self):
self.petsList.sort(key=lambda p: p.entryDate)
counter = 0
for date, pets in groupby(self.petsList, key=lambda p: p.entryDate):
pet_list = list(pets)
print(f'first {pet_list}')
print(f'second {pet_list}')
#first [<__main__.Petshop object at 0x7fcd1001e430>, <__main__.Petshop object at 0x7fcd504428b0>, <__main__.Petshop object at 0x7fcd50446d00>]
#second [<__main__.Petshop object at 0x7fcd1001e430>, <__main__.Petshop object at 0x7fcd504428b0>, <__main__.Petshop object at 0x7fcd50446d00>]
- petlist 是一個寵物串列,而不是一個 pet_names 串列,所以 if 陳述句永遠不會為真,我們可以使用下面的方法解決這個問題。
def printPets(self):
self.petsList.sort(key=lambda p: p.entryDate)
counter = 0
for date, pets in groupby(self.petsList, key=lambda p: p.entryDate):
pet_list = list(pets)
pet_names = [p.name for p in pet_list]
print("---------------", ls[0], '------------------')
for pet in pet_list:
print("Name:", pet.name)
print("Owner name:", pet.ownerName)
if pet.name in pet_names:
counter = 1
print('There are ',counter,'pets with the same name')
- 計數總是等于寵物的數量。您只想檢查未見過的寵物以計算重復的寵物,因為每只寵物在 pet_list 中至少出現一次。
def printPets(self):
self.petsList.sort(key=lambda p: p.entryDate)
counter = 0
for agg, vals in groupby(self.petsList, key=lambda p: p.entryDate):
_vals = list(vals)
name_list =[x.name for x in _vals]
print("---------------", agg, '------------------')
for i, pet in enumerate(_vals):
print("Name:", pet.name)
print("Owner name:", pet.ownerName)
if pet.name in name_list[:i]:
counter = 1
print('There are ',counter,'pets with the same name')
我在 (2) 中還包含了一個小修復,通過取消縮進列印陳述句來防止列印中間計數。
uj5u.com熱心網友回復:
也許這不是最好的方法,但在這里。應該為每個組重置計數器,正如@Matiiss 所說,ls[1] 是 PetShop 類的實體,因此將其保存在變數中可能會更好,訪問其屬性可以使其更加清晰。
from itertools import groupby
class Petshop():
def __init__(self, entryDate, name, ownerName):
self.entryDate = entryDate
self.name = name
self.ownerName = ownerName
class Pets():
def __init__(self):
self.petsList = []
def addPets(self, entryDate, name, ownerName ):
entry_pet = Petshop(entryDate, name, ownerName)
self.petsList.append(entry_pet)
def printPets(self):
self.petsList.sort(key=lambda p: p.entryDate)
for group in groupby(self.petsList, key=lambda p: p.entryDate):
ls = list(group)
data = list(ls[1])
names= []
print("--------", ls[0], "--------")
index = 0
for pet in list(data):
if pet.name in names :
repeatedName = pet.name
index = 1
print("Name:", pet.name)
names.append(pet.name)
print("Owner:", pet.ownerName)
if index == len(data):
print("There are", names.count(repeatedName), "pets with the same name")
names = []
pet = Pets()
pet.addPets('04/13/2021','Pinky', 'David Smith')
pet.addPets('07/10/2020', 'Charlie', 'Joe Davis')
pet.addPets('04/13/2021','Pinky', 'Daniel Trincot')
pet.addPets('07/10/2020', 'Kenny', 'Susan Jones')
pet.addPets('12/22/2018', 'Teddy', 'Carl Johnson')
pet.addPets('07/10/2020', 'Kenny', 'Richard Campbell')
pet.addPets('04/13/2021','Max', 'Bryan Miller')
pet.addPets('07/10/2020', 'Buddy', 'Kathy Brown')
pet.addPets('07/10/2020', 'Kenny', 'John Brown')
pet.printPets()
這是我得到的輸出
-------- 04/13/2021 --------
Name: Pinky
Owner: David Smith
Name: Pinky
Owner: Daniel Trincot
Name: Max
Owner: Bryan Miller
There are 2 pets with the same name
-------- 07/10/2020 --------
Name: Charlie
Owner: Joe Davis
Name: Kenny
Owner: Susan Jones
Name: Kenny
Owner: Richard Campbell
Name: Buddy
Owner: Kathy Brown
Name: Kenny
Owner: John Brown
There are 3 pets with the same name
-------- 12/22/2018 --------
Name: Teddy
Owner: Carl Johnson
There are 0 pets with the same name
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/344647.html
上一篇:批處理檔案中的反向換行
