You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

合并关联数组并实现账户与客户信息对应打印的技术问题

解决账户与客户信息一一对应打印的问题

看起来你已经在创建Customer对象的时候,把对应的Account关联进去了(代码里customer = Customer(..., self._accounts[len(self._customers)])这一步做得很对!),现在只需要调整打印的逻辑就能实现你想要的合并输出效果。

首先先纠正你当前打印代码里的小错误:你现在的循环里用了print(customer)和print(account),这两个变量都是循环外最后创建的对象,不是当前循环的i,所以不管循环多少次,打印的都是同一个内容。

方案1:利用Customer对象中已关联的Account

既然每个Customer已经持有对应的Account引用,直接遍历_customers列表,依次打印客户信息和其关联的账户信息即可:

# 替换你原来的两个for循环
for customer in self._customers:
    print(customer)
    print(customer._account)  # 这里假设Customer类里存储账户的属性是_account,你可以根据实际类定义调整属性名

如果Customer类里的账户属性不是_account,比如你创建的时候是作为参数传入并存在了其他属性(比如account),就改成对应的属性名就行。

方案2:通过索引同时遍历两个列表

如果你更倾向于直接操作两个列表,也可以用zip函数把_customers和_accounts配对,然后逐个打印:

for customer, account in zip(self._customers, self._accounts):
    print(customer)
    print(account)

这个方法的前提是两个列表的长度完全一致,且索引位置一一对应(你的代码逻辑里已经保证了这一点,因为创建第n个客户时取的是第n个账户)。

验证效果

调整后,打印出来的内容就会是你想要的格式:

Customer no. 586425 Name: Tony Age: 41 City: Hobart
Account no. 246805: Type: Saving Balance: 1500.0 Maximum transaction amount: 4000.0

另外,如果你想让两个信息的格式更紧凑,也可以自定义Customer类的__str__方法,把账户信息也包含进去,这样直接打印customer就能输出合并后的内容,比如:

class Customer:
    # 其他代码...
    def __str__(self) -> str:
        cust_str = f"Customer no. {self._custNo} Name: {self._custNm} Age: {self._age} City: {self._city}"
        acc_str = str(self._account)
        return f"{cust_str}\n{acc_str}"

这样之后,只需要for customer in self._customers: print(customer)就能直接输出合并后的内容了。

内容的提问来源于stack exchange,提问作者Pyxis Black

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 13:07:30