我有以下包含元组的列表:
ov=[(0,), (1,), (0,), (0,), (0,), (0,), (1,), (1,), (1,), (1,), (1,), (0,), (1,), (1,), (1,), (0,), (1,), (1,), (1,), (1,), (1,), (None,)]
我现在希望将所有1
值和先前0
值存储在单独的列表中。
每次存储的最后一个值应为0
,或者如果存在值None
,则不应存储该值。
所以我想要的结果是:
result =[1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1]
我已经具有以下功能:
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)
然后是for循环:
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)
输出:
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,)
有人可以帮助我转换此循环,以便返回所需结果吗?
答案 0 :(得分:1)
希望这段代码中的注释不言自明:
cat file.txt | head -1000000 | grep -o "\bword\b" | wc -l
输出:
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)
答案 1 :(得分:1)
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)