LoginSignup
0
0

More than 1 year has passed since last update.

Python ランダムな数列を作成する方法。重複有無、全列挙

Last updated at Posted at 2021-07-13

指定した範囲を列挙する

rangeを使えば、範囲の数列を作ることができます。

lst = list(range(0, 10))
print(*lst)
# 0 1 2 3 4 5 6 7 8 9

指定した範囲から、重複のないランダムな数列

random.sampleを使用して、重複のないランダムな数列を作れます。

import random

lst = list(range(0, 10))
print(*random.sample(lst, len(lst)))
# 8 9 7 6 0 3 1 2 5 4

# 別の書き方
lstlen = 10
print(*random.sample(list(range(0, 10)), lstlen))

指定した範囲から、重複ありでランダムな数列

import random

lst = list(range(0, 10))
print(*random.choices(lst, k=len(lst)))
# 2 4 7 5 6 1 7 9 3 2

# 別の書き方
lstlen = 10
print(*random.choices(list(range(0, lstlen)), k=lstlen))

とりうる組み合わせを全て列挙する

import itertools

lst = list(range(0, 3))
for i in itertools.permutations(lst):
    print(*i)
# 0 1 2
# 0 2 1
# 1 0 2
# 1 2 0
# 2 0 1
# 2 1 0

# 別の書き方
lstlen = 3
for i in permutations(list(range(0, lstlen))):
    print(*i)

おまけ

rangeのさまざまな使い方

list(range(10))
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
list(range(1, 11))
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
list(range(0, 30, 5))
# [0, 5, 10, 15, 20, 25]
list(range(0, 10, 3))
# [0, 3, 6, 9]
list(range(0, -10, -1))
# [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
list(range(0))
# []
list(range(1, 0))
# []

参考

【Python】リストや文字列の要素をランダムに抽出する(random.choice, choices, sample) | Hbk project

random --- 擬似乱数を生成する — Python 3.9.4 ドキュメント

組み込み型 — Python 3.9.4 ドキュメント

itertools --- 効率的なループ実行のためのイテレータ生成関数 — Python 3.9.4 ドキュメント

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0