我有一个类,里面有一系列循环。每个循环都使用 pandas.dataframe 将数据添加到可以作为实例属性调用的新列表。
data = [player_stats, captured_creatures, item_list, moveset, opponents_stats, player_inventory]
class Battle():
def __init__(self,data):
stuff,stuff1,stuff2,stuff3,stuff4,stuff5 = [], [], [], [], [], []
for t in data.player_stats.loc[0, :]:
stuff.append(t)
for t in data.captured_creatures.loc[0, :]:
stuff1.append(t)
for t in data.item_list.loc[0, :]:
stuff2.append(t)
for t in data.moveset.loc[0, :]:
stuff3.append(t)
for t in data.opponents_stats.loc[0, :]:
stuff4.append(t)
for t in data.player_inventory.loc[0, :]:
stuff5.append(t)
self.stuff = stuff
self.stuff1 = stuff1
self.stuff2 = stuff2
self.stuff3 = stuff3
self.stuff4 = stuff4
self.stuff5 = stuff5
有什么方法可以减少重复吗?我知道我可以使用以下方法获取实例名称:
instances = [attr for attr in dir(data)][-6:]
我不确定如何使用该信息来创建嵌套循环。
我希望这是清楚的。
我不确定您的数据是否是独立的 pandas 数据框,因此数据将是 pandas df 数组。因此,您可以使用 setattr 方法进行总结。这是一个例子:
# Sample data setup
player_stats = pd.DataFrame({
'HP': [100],
'Attack': [50],
'Defense': [40]
})
captured_creatures = pd.DataFrame({
'Name': ['Dragon'],
'Level': [10],
'Type': ['Fire']
})
item_list = pd.DataFrame({
'Item': ['Potion', 'Elixir'],
'Quantity': [3, 1]
})
moveset = pd.DataFrame({
'Move': ['Fireball', 'Slash'],
'Power': [40, 30]
})
opponents_stats = pd.DataFrame({
'HP': [120],
'Attack': [60],
'Defense': [45]
})
player_inventory = pd.DataFrame({
'Gold': [500],
'Keys': [2],
'Potions': [1]
})
# Combine the data into a list as expected by the Battle class
data = [player_stats, captured_creatures, item_list, moveset, opponents_stats, player_inventory]
fields = ['player_stats', 'captured_creatures', 'item_list', 'moveset', 'opponents_stats', 'player_inventory']
# Define the Battle class as provided
class Battle():
def __init__(self, data):
for name, df in zip(fields, data):
setattr(self, f"{name}", df.loc[0].tolist())
# Instantiate a Battle object with the sample data
battle = Battle(data)
# Display the results
print("Player Stats:", battle.player_stats)
print("Captured Creatures:", battle.captured_creatures)
print("Item List:", battle.item_list)
print("Moveset:", battle.moveset)
print("Opponents Stats:", battle.opponents_stats)
print("Player Inventory:", battle.player_inventory)
enter code here
希望有帮助!