这里的函数只生成一个0和1的随机列表。它可以在游戏中使用。所以我需要获取binary_gen生成的列表并将其转换为字符串。我尝试过使用.join,但我收到了一条错误消息。有没有办法让我将binary_gen的输出转换为字符串?或者有另一种方法可以生成0和1的随机序列吗?
import random
def random_binary():
min_length = 4
max_length = 8
binary_gen = [random.randrange(0,2,1) for _ in range \
(random.randint(min_length,max_length))]
print (binary_gen)
random_binary()
更新
import random
def random_binary():
min_length = 4
max_length = 8
binary_gen = [random.randrange(0,2,1) for _ in range \
(random.randint(min_length,max_length))]
binary_string = "".join(binary_gen)
print (binary_string)
random_binary()
我得到: TypeError:序列项0:预期的str实例,int found
答案 0 :(得分:2)
生成随机字符串序列的0和随机长度从4到8:
>>> from random import randint
>>> ''.join(str(randint(0, 1)) for i in range(randint(4, 8)))
'0010111'
或者,更直接地说:
>>> from random import choice, randint
>>> ''.join(choice('01') for i in range(randint(4, 8)))
'101101'
计算一串零和一串1
的数量:
>>> s = '0011100'
>>> len(s.replace('0', ''))
3
或者:
>>> sum(c=='1' for c in s)
3
答案 1 :(得分:1)
import random
def random_binary(min_length=4, max_length=8):
size = random.randint(min_length, max_length)
return ''.join(str(random.randint(0, 1)) for _ in range(size))
print(random_binary())
我的猜测是你得到的错误类似于TypeError: sequence item 0: expected str instance, int found
,因为你试图加入数字而不是字符串。上面的str(...)
是使此代码有效的原因。
答案 2 :(得分:1)
请尝试以下:
import random
def random_binary():
min_length = 4
max_length = 8
binary_gen = [random.randrange(0,2,1) for _ in range \
(random.randint(min_length,max_length))]
_str = ''
for i in binary_gen:
_str += str(i)
return _str
def count_zeros(s):
count = 0
for i in s:
if i == '0':
count += 1
return count
它生成' 111010'串。 count_zeros(s)
将返回输入字符串