我正在编写一个生成n个布尔值列表的函数。假设返回的列表是[True, False, True, True, False]
。我需要根据布尔值生成列表,以识别相同值的条纹。因此,在这种情况下的结果将是[1, 1, 2, 1]
。出于某种原因,我的代码不包括上次运行。在提供的示例中,我将生成[1, 1, 2]
。我似乎无法弄清楚为什么会发生这种情况以及如何解决它。提前谢谢!
#Makes list of bools
def bools(p, n):
return (rand(n) < p)
#Makes list that counts successive values
def succession(p, n):
run = bools(p, n)
print run
successionlist = []
counter = 1
for j in range(1, n):
if run[j] == run[j - 1]:
counter = counter + 1
else:
successionlist.append(counter)
print successionlist
counter = 1
答案 0 :(得分:1)
只有在获得不同的值时才附加。你需要再次追加
successionlist = []
counter = 1
for j in range(1, n):
if run[j] == run[j - 1]:
counter = counter + 1
else:
successionlist.append(counter)
print successionlist
counter = 1
successionlist.append(counter)
print successionlist
答案 1 :(得分:0)
您需要在 succesionlist.append(counter)
循环之后将<{1}}添加到您的函数正文中,然后 。这样做的原因是,当值从for
更改为True
时,您只会将计数器附加到列表中,反之亦然,但即使您当前的值,该值也不会在最后一个值之后更改计算最终结果所需的元素数。随后你总是需要在循环后附加计数器。
答案 2 :(得分:0)
好吧,如果最后两个元素不同,你只会在继承列表中追加一个值。因此,如果您的输入数组以序列结束,则循环将运行并仅增加计数器而不将其添加到结果列表中。当你在最后一个元素时,我会尝试检查这种情况,并且与前一个元素相同。
successionlist = []
counter = 1
for j in range(1, n):
if run[j] == run[j - 1]:
counter = counter + 1
# Check for the last element
if j == n-1:
successionlist.append(counter)
else:
successionlist.append(counter)
print successionlist
counter = 1
print successionlist
答案 3 :(得分:0)
尝试这样的事情:
list=[True, False, True, True, False]
def succession(list):
result = []
saved = -1
for value in list:
int_value = int(value)
if int_value == saved:
result[-1] += 1
else:
result.append(1)
saved = int_value
return result
print succession(list)
答案 4 :(得分:0)
最简单的可能是在开头而不是在继承结束时追加:
#Makes list of bools
def bools(p, n):
return (rand(n) < p)
#Makes list that counts successive values
def succession(p, n):
run = bools(p, n)
print run
lastvalue = None
successionlist = []
for item in run:
if item is not lastvalue:
lastvalue = item
successionlist.append(0)
successionlist[-1] += 1
答案 5 :(得分:-1)
这样做:
counter = 1
for j in range(1, n):
if run[j] == run[j - 1]:
counter = counter + 1
else:
successionlist.append(counter)
print successionlist
counter = 1
else:
successionlist.append(counter)