生成彩票号码-将R语句转换为Python



我在R中有以下函数来生成10个随机彩票号码:

 sprintf("%05d", sort(sample(0:99999, 10)))

输出:

"00582" "01287" "01963" "10403" "13274" "17705" "23798" "32808" "33668" "35794"

我已经将其转换为Python,如下所示:

 print(sorted(sample(range(99999), 10)))

输出:

[208, 10724, 12078, 27425, 34903, 49666, 60057, 67482, 68730, 78811]

在第一种情况下,我得到的数字是5位数,而在第二种情况中,数字最多可以有5位数,,但也可以更少

那么,有没有类似的方法可以获得5位数字的列表(或第一种情况下的字符串)?

您可以将str.formatmap组合为一个

print(*map('{:05}'.format, sorted(sample(range(99999), 10))))

此上下文中的星号将打开参数列表的包装。换句话说,它从给定的可迭代(在本例中为map)生成位置参数。

您也可以将彩票号码存储为字符串列表

# Again using a map
ns = list(map('{:05}'.format, sorted(sample(range(99999), 10))))
# Using a list comprehension
ns = ['{:05}'.format(n) for n in sorted(sample(range(99999), 10))]

请注意,python的range是打开的,如[start,stop)中所示,因此使用

range(100000)

用于0到99999的值范围。

您需要格式化string

out = []
for number in sorted(sample(range(99999), 10))):
    out.append('{:05d}'.format(number))
print(out)

最新更新