Python 中带有 for 循环的 Zip 方法

Zip method with for loop in Python

我试图从 4 个不同的列表中获取以下输出,我需要调用 address_machine 方法并将项目从列表中压缩并使用 for 循环遍历新列表然后打印它们在新行上 --> 下面的预期输出:

["T Cruise","D Francis","C White"]
["2 West St","65 Deadend Cls","15 Magdalen Rd"]
["Canterbury", "Reading", "Oxford"]
["CT8 23RD", "RG4 1FG", "OX4 3AS"]

我的方法是这样的:

def address_machine(name, street_address, town, postcode):
    address = "{0},{1},{2},{3}".format(name, street_address, town, postcode)
    return address

print([address_machine(name, street_address, town, postcode) for name, street_address, town, postcode in
       zip(["T Cruise", "D Francis", "C White"], ["2 West St", "65 Deadend Cls", "15 Magdalen Rd"],
           ["Canterbury", "Reading", "Oxford"], ["CT8 23RD", "RG4 1FG", "OX4 3AS"])])

这是一个问题,因为我得到的输出看起来像这样,并且全部在一行中:

['T Cruise,2 West St,Canterbury,CT8 23RD', 'D Francis,65 Deadend Cls,Reading,RG4 1FG', 'C White,15 Magdalen Rd,Oxford,OX4 3AS']

我需要如何编写此 Python adress_machine 函数才能获得预期的输出?

您可以使用正常的 for-loop

for name, street_address, town, postcode in zip(["T Cruise", "D Francis", "C White"], ["2 West St", "65 Deadend Cls", "15 Magdalen Rd"],
       ["Canterbury", "Reading", "Oxford"], ["CT8 23RD", "RG4 1FG", "OX4 3AS"]):

     print([name, street_address, town, postcode])

或首先创建包含所有元素的列表,然后 for 循环显示它

data = [[name, street_address, town, postcode] for name, street_address, town, postcode in zip(["T Cruise", "D Francis", "C White"], ["2 West St", "65 Deadend Cls", "15 Magdalen Rd"],
       ["Canterbury", "Reading", "Oxford"], ["CT8 23RD", "RG4 1FG", "OX4 3AS"])]

for item in data:
    print(item)

并且不明白为什么要使用函数 address_machine(),如果您希望得到列表的结果,它会将列表转换为字符串。

将您的 address_machine 函数更改为:

def address_machine(name, street_address, town, postcode):
    return "{0},{1},{2},{3}\n".format(name, street_address, town, postcode)

您必须 return 一个额外的换行符。并且直接 return 而不是先定义一个变量使得代码更短 !