random.sample()函数和str的join()函数

题目:
随机生成100个统一号码段的(比如180)手机号码
random.sample(‘sequence’, x)

代码:
import random
for i in range(0,100):
list1 = random.sample(range(0,10), 8)
list2 = [str(x) for x in list1] #将list1中整型元素转为str类型
num = ‘180’
print(num+”.join(list2))

相关函数
range()范围只能是整数

random.sample(population, k)
返回从总体序列或集合(potution)中选择的唯一元素的 k 长度列表(list)。用于随机抽样,无需更换。
str.join(iterable)
返回一个字符串,它是 iterable iterable 中字符串的并置。如果 iterable 中有任何非字符串值,包括 bytes 对象,则会引发 TypeError。元素之间的分隔符是提供此方法的字符串。
返回以str为分隔符连接iterable中元素的字符串
iterable中元素必须为字符串类型
此题中 list1 = random.sample(range(0,10), 8)返回的list1列表为int类型
故要转为str类型才能调用join函数

否则报错:sequence item 0: expected str instance, int found

猜你喜欢

转载自blog.csdn.net/weixin_42983044/article/details/82084525
今日推荐