简体   繁体   中英

How to loop through item in two list in python one by one

I was trying to loop through two list which contain two different user, the for loops works when there's item in both list, but it won't works when one of the list doesn't have any item.

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)

No item in admin_list

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

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

Just need to implement some if's. Example

a=[]

if a:
  

Put after your lists but before your for

Zip function will take the shortest length of array. You need to check null or empty in this case.

Please check reference. How to iterate through two lists in parallel?

just check if empty or not

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM