Reputation: 29
I have following list containing tuples:
ov=[(0,), (1,), (0,), (0,), (0,), (0,), (1,), (1,), (1,), (1,), (1,), (0,), (1,), (1,), (1,), (0,), (1,), (1,), (1,), (1,), (1,), (None,)]
I now want all the values that are 1
and have the previous value of 0
stored in a separate list.
The last value that is stored each time should be 0
or if there is the value None
this should not be stored.
So I would like a result that is:
result =[1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1]
I already got following function:
def previous_and_next(something):
prevs, items, nexts = tee(something, 3)
prevs = chain(["NONE"], prevs)
nexts = chain(islice(nexts, 1, None), ["NONE"])
return zip(prevs, items, nexts)
And following for loop:
for previous, item, nxt in previous_and_next(ov):
if item[0]==1 and previous[0]==0 and nxt[0]==1:
print("This is the start value of my wanted values")
print(previous)
print(item)
print(nxt)
with the output:
This is the start value of my wanted values
(0,)
(1,)
(1,)
This is the start value of my wanted values
(0,)
(1,)
(1,)
This is the start value of my wanted values
(0,)
(1,)
(1,)
Can someone help me transform this loop so it returns desired outcome?
Upvotes: 0
Views: 68
Reputation: 3722
Hope the comments in this code are self-explanatory:
ov=[(0,), (1,), (0,), (0,), (0,), (0,),
(1,), (1,), (1,), (1,), (1,), (0,),
(1,), (1,), (1,), (0,), (1,), (1,), (1,), (1,), (1,), (None,)]
my_len = len(ov)
result = []
i = 0
while (i < my_len):
# Skip over the zeros
while ((i < my_len) and not ov[i][0]):
i += 1
# Gobble up the 1's
while ((i < my_len) and ov[i][0]):
result.append(1)
i += 1
# Append the 0 appearing after the 1's
if ((i < my_len) and (ov[i][0] is not None)):
result.append(0)
print(result)
Output:
[1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1]
Upvotes: 1
Reputation: 1317
my_result = []
is_zero = None
for o in ov:
if o[0]==1:
my_result.append(o[0])
is_zero = False
elif o[0]==0 and is_zero == False:
my_result.append(o[0])
is_zero=True
print(my_result)
Upvotes: 1