Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
zip lists with condition
#1
Guys,

Can I zip lists but ONLY if a list isn't empty?

a = [1,2,3,4,5]
b = [ [], [], ["a","b"], ["e","h"], []] 
c = zip(a, b)
d = []
for i in c:
    for j in i:
    	if anyj: 
            d.append(i)
    	else:
        	pass
print(d)
c returns: [(1, []), (2, []), (3, ['a', 'b']), (4, ['e', 'h']), (5, [])]
#BUT I don't care for c index 1, 2, 5 since they have a empty list.
Have do I alter "d[]"? Or does zip provide a conditonal zip?
Reply
#2
Hello,

I suggest this:

a = [1,2,3,4,5]
b = [ [], [], ["a", "b"], ["e", "f"], [] ]
l = [elt for elt in zip(a,b) if elt[1]]
Best Regards,

Nicolas TATARENKO
Reply
#3
@Nicolas TATARENKO,

Awesome. I knew it could be handled much easier!
Reply
#4
if the first list is just index/list of consecutive numbers, you can use enumerate()
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
burans sugesition:

b = [ [], [], ["a", "b"], ["e", "f"], [] ]
l = [elt for elt in enumerate(b) if elt[1]]
Each elt object is a tuple of index and element(s) from b.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#6
keep in mind that you can unpack the tuple. (so it is more readable and indices are not required)
l = ['a', 'b']
for i, val in enumerate(l): print(i,val)
Output:
0 a 1 b
Reply
#7
And if you want to start with 1:

enumerate(ITERABLE, 1)
Your indexing starts with 1
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Split dict of lists into smaller dicts of lists. pcs3rd 3 2,367 Sep-19-2020, 09:12 AM
Last Post: ibreeden
  else condition not called when if condition is false Sandz1286 10 5,849 Jun-05-2020, 05:01 PM
Last Post: ebolisa
  [HELP] Nested conditional? double condition followed by another condition. penahuse 25 7,909 Jun-01-2020, 06:00 PM
Last Post: penahuse
  sort lists of lists with multiple criteria: similar values need to be treated equal stillsen 2 3,259 Mar-20-2019, 08:01 PM
Last Post: stillsen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020