如何在python中使用多个forloop保存为列表

2024-04-27 17:57:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个专栏:

^{tb1}$

我想将ID和姓名组合在一起并另存为列表。例如,['ID11属于大卫']。我该怎么做

到目前为止我试过什么

op=[]
for i, j in itertools.product(data['ID'], data['Name']):
        dt = str('The ID' + str(i)+ 'belongs to' +j)
        op.append(dt)
        print(dt)

输出多次保存为列表。我该怎么纠正呢

期望输出:

['The ID 11 belongs to David', 'The ID 12 belongs to Alex', 'The ID 13 belongs to Alice', 'The ID 14 belongs to Mark', 'The ID 15 belongs to Maria']

Tags: thetoid列表fordatadt大卫
1条回答
网友
1楼 · 发布于 2024-04-27 17:57:56

所需的输出不是列表data['ID']data['Name']的叉积

所以不要使用itertools.product,我想您应该使用^{}zip(a, b)返回元组生成器,将lista的第一个元素与listb的第一个元素匹配,然后是两个列表的第二个元素,然后是第三个元素,依此类推

您还可以将代码缩短为列表理解,并使用f字符串,使其更具Python风格:

a = [13, 14, 15]
b = ["mark", "alice", "bob"]

result = [ f'ID {i} belongs to {j}' for i,j in zip(a,b) ]
print(result)

该代码的输出将是:

['ID 13 belongs to mark', 'ID 14 belongs to alice', 'ID 15 belongs to bob']

相关问题 更多 >