简体   繁体   中英

Fill missing values in lists

I have a list which consists of 0's and 1's. The list should ideally look like this 0,1,0,1,0,1,0,1,0,1,0,1,0,1.....

But due to some error in logging, my list looks like this: 0,1,0,1,1,1,0,1,0,0,0,1,0,1.... As one can clearly there are some missed 0's and 1's in middle. How can I fix this list to add those 0's and 1's in between the missing elements so as to get to the desired list values.

Here is the code used by me, this does the task for me but it is not the most pythonic way of writing scripts. So how can I improve on this script?

l1 = [0,1,0,1,1,1,0,1,0,0,0,1,0,1]
indices = []
for i in range(1,len(l1)):
    if l1[i]!=l1[i-1]:
        continue
    else:
        if l1[i]==0:
            val=1
        else:
            val=0
        l1.insert(i, val)

EDIT

As asked in the comments, Let me explain why is this important rather than generating 1's and 0's. I have TTL pulse coming ie a series of HIGH(1) and LOW(0) coming in and simultaneously time for each of these TTL pulse is logged on 2 machines with different clocks.

Now while machine I is extremely stable and logging each sequence of HIGH(1) and low(1) accurately, the other machine ends up missing a couple of them and as a result I don't have time information for those.

All I wanted was to merge the missing TTL pulse on one machine wrt to the other machine. This will now allow me to align time on both of them or log None for not received pulse.

Reason for doing this rather than correcting the logging thing (as asked in comments) is that this is an old collected data. We have now fixed the logging issue.

why would you have a list of 0,1,0,1,0,1 ? there is no good reason i can think of. oh well thats beyond the scope of this question i guess...

list(itertools.islice(itertools.cycle([0,1]),expected_length))

You can try something like this:

from itertools import chain

l1 = [0,1,0,1,1,1,0,1,0,0,0,1,0,1]

c = max(l1.count(0), l1.count(1))
print list(chain(*zip([0]*c,[1]*c)))

Output:

[0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1]

Just multiply a new list.

>>> l1 = [0,1,0,1,1,1,0,1,0,0,0,1,0,1]
>>> l1
[0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1]
>>> [0,1] * (len(l1)//2)
[0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1]

If the list has an odd number of elements, add the necessary 0 :

>>> l2 = [0,1,0,1,1,1,0,1,0,0,0,1,0,1,0]
>>> l2_ = [0,1] * (len(l1)//2)
>>> if len(l2)%2: l2_.append(0)
...
>>> l2
[0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0]
>>> l2_
[0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0]

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