gpt4 book ai didi

Python-按属性将类的实例组合在一起

转载 作者:太空宇宙 更新时间:2023-11-04 04:36:01 25 4
gpt4 key购买 nike

我想根据属性值将类的实例组合在一起。假设我有以下类(class):

class location:

def __init__(self,x_coord,y_coord,text):
self.x_coord=x_coord
self.y_coord=y_coord
self.text=text

def __repr___(self):
return self.text

mylist=[location(1,0,'Date'),location(5,0,'of'),location(8,0,'Entry'), location(28,0,'Date'),location(29,0,'of'),location(30,0,'Birth') ]

如果 x_coord 属性的差异小于 10,我想对我的类列表进行分组,这样

mygroupedlist=[['Date','of','Entry'],['Date','of','Birth']]

有人可以给我提示吗?

最佳答案

如果您不介意使用外部库,您可以通过使用 numpy 和 pandas 获得更好的性能。

# Create a dataframe
df = pd.DataFrame(mylist, columns=['locations'])
# Create columns representing the 'x' coords, and the 'text'
df['x'] = df['locations'].apply(lambda x: x.x_coord)
df['text'] = df['locations'].apply(lambda x: x.text)
# Create an indicator array that tells you whether the current row is within 10 of the previous row
closeness_indicator = np.isclose(df['x'], df['x'].shift(1), atol=10)
# Negate that, then take the cumulative sum to get groups:
groups = (~closeness_indicator).cumsum()
# GRoup by that array, then create lists from the grouped text:
df.groupby(groups)[text].apply(list)

输出:

1    [Date, of, Entry]
2 [Date, of, Birth]
Name: text, dtype: object

关于Python-按属性将类的实例组合在一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51715184/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com