【问题标题】:How can I print over multiple lists in a loop while being mapped to each other?如何在相互映射时循环打印多个列表?
【发布时间】:2021-04-23 17:36:57
【问题描述】:

通过使用我制作的函数,我想只使用一个循环打印所有员工的记录。

     Record = [["ali", "Mazen", "Fida", "Nader", "Majd"], ["Tutor", "IT", "Manager", "PR", "Clerk"]]
    def Netsal(salary):
        bonus=0
        if salary<2000:
            bonus = 300
        elif salary>=4000:
            bonus = 100
        else:
            bonus = 200
        return salary + bonus
    Sal=[2200,1600,4000,2000,1400]
    holder=[]
    for base_salary in Sal:
        total_salary=Netsal(base_salary)
        holder.append(total_salary)
    for total_salary in Netsal(base_salary):
        print(Record, total_salary)

在打印方面我有点迷茫,因为我需要输出如下:

Mazen - IT : 1900

所以记录中的两个子列表也需要和奖金一起映射到新的工资列表中。

另外,我需要遍历列表并以上面显示的格式打印所有值。

【问题讨论】:

  • 你在用 IT 打印阿里什么? Ali 不是 Tutor 吗?
  • 不好意思,我好久没睡觉了

标签: python list loops printing


【解决方案1】:

在运行最后一个循环打印之前,您有三个列表:

  • Record[0] 是一个包含名称的列表
  • Record[1] 是一个包含部门的列表
  • holder 是一个包含净工资的列表。

zip() 可以采用任意数量的可迭代对象(列表是可迭代对象),并从每个可迭代对象返回包含一个元素的元组。 for 语句可以将此元组解包成相同数量的变量。

for person, department, salary in zip(Record[0], Record[1], holder):
    print(f"{person} - {department} : {salary}")

您的代码有一个不必要的循环。您可以删除填充holder 的循环并将该逻辑合并到我上面显示的zip 循环中,就像这样,使用zip() 中的Sal 列表:

for person, department, base_salary in zip(Record[0], Record[1], Sal):
    net_salary = Netsal(base_salary)
    print(f"{person} - {department} : {net_salary}")

print() 语句中,我使用f-strings 进行字符串插值

【讨论】:

  • 这就是我所做的,非常感谢。成功了!
猜你喜欢
  • 1970-01-01
  • 2021-03-13
  • 1970-01-01
  • 2020-07-16
  • 1970-01-01
  • 1970-01-01
  • 2020-12-20
  • 1970-01-01
  • 2018-12-04
相关资源
最近更新 更多