【问题标题】:How to loop through item in two list in python one by one如何在python中的两个列表中一个一个地循环遍历项目
【发布时间】:2021-05-04 07:30:10
【问题描述】:

我试图遍历包含两个不同用户的两个列表,当两个列表中都有项目时,for 循环有效,但当其中一个列表没有任何项目时,它将不起作用。

customer_list = [["ctm1","Jackson","abc"],["ctm2","Kaijun","edf"]]
  admin_list  = [["adm1","Jackson","martinez"],["adm2","Littsen","Lit"]]

for customer,admin in zip(customer_list, admin_list):
     print(customer,admin)

admin_list 中没有项目

customer_list = [["ctm1","Jackson","abc"],["ctm2","Kaijun","edf"]]
admin_list = []

for customer,admin in zip(customer_list, admin_list):
     print(customer,admin)

【问题讨论】:

  • 预期输出是什么?
  • 最好有but it won't works when one of the list doesn't have any item 的示例代码和预期的输出。
  • 只需要一个 if 语句来判断其中一个列表是否为空。
  • @shahkalpesh 我已经编辑了帖子并提供了示例代码,我希望 for 循环仍然能够打印(客户)
  • 当您想使用 zip 时,一个选项是使两个列表的长度相同。

标签: python for-loop


【解决方案1】:

只需要实现一些如果。示例

a=[]

if a:
  

放在你的列表之后,但在你的 for 之前

【讨论】:

    【解决方案2】:

    只检查是否为空

    l1 = [["ctm1","Jackson","abc"],["ctm2","Kaijun","edf"]]
    l2 = [["adm1","Jackson","martinez"],["adm2","Littsen","Lit"]]
    
    
    l3 = zip(l1, l2) if l1 and l2 else l1 if l1 else l2
    
    for x in l3:
        print(x)
    
    

    【讨论】:

      【解决方案3】:

      Zip 函数将采用最短长度的数组。在这种情况下,您需要检查 null 或 empty。

      请检查参考。 How to iterate through two lists in parallel?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-06-10
        • 1970-01-01
        • 2018-12-24
        • 1970-01-01
        • 2019-09-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多