gpt4 book ai didi

Python:遍历对象列表中的对象列表

转载 作者:太空狗 更新时间:2023-10-29 22:20:08 25 4
gpt4 key购买 nike

我制作了两个类,分别称为“房子”和“ window ”。然后我做了一个包含四个房子的 list 。 House 的每个实例都有一个 Windows 列表。我正在尝试遍历每个房子的 window 并打印它的 ID。但是,我似乎得到了一些奇怪的结果 :S 我将不胜感激任何帮助。

#!/usr/bin/env python

# Minimal house class
class House:
ID = ""
window_list = []

# Minimal window class
class Window:
ID = ""

# List of houses
house_list = []

# Number of windows to build into each of the four houses
windows_per_house = [1, 3, 2, 1]

# Build the houses
for new_house in range(0, len(windows_per_house)):

# Append the new house to the house list
house_list.append(House())

# Give the new house an ID
house_list[new_house].ID = str(new_house)

# For each new house build some windows
for new_window in range(0, windows_per_house[new_house]):

# Append window to house's window list
house_list[new_house].window_list.append(Window())

# Give the window an ID
house_list[new_house].window_list[new_window].ID = str(new_window)

#Iterate through the windows of each house, printing house and window IDs.
for house in house_list:
print "House: " + house.ID

for window in house.window_list:
print " Window: " + window.ID

####################
# Desired output:
#
# House: 0
# Window: 0
# House: 1
# Window: 0
# Window: 1
# Window: 2
# House: 2
# Window: 0
# Window: 1
# House: 3
# Window: 0
####################

最佳答案

目前您正在使用 class attributes instead of instance attributes .尝试将您的类定义更改为以下内容:

class House:
def __init__(self):
self.ID = ""
self.window_list = []

class Window:
def __init__(self):
self.ID = ""

您的代码现在的方式 House 的所有实例都共享相同的 window_list

关于Python:遍历对象列表中的对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7408237/

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