teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

1

追加

2021/03/23 07:56

投稿

ppaul
ppaul

スコア24672

answer CHANGED
@@ -1,3 +1,45 @@
1
1
  comments = "".join([e[random.randint(0, 2)] for e in commentsElements])
2
2
 
3
- です。
3
+ です。
4
+ これは、commentsElementsの中のリストの長さが3でないとうまく動作しません。
5
+ それぞれのリストの長さが違っていても動くようにするには以下にすると良いです。
6
+ random.choiceを使えば、それぞれの長さを気にする必要がなくなります。
7
+
8
+ ```python
9
+ import random
10
+
11
+ def randomcomment(cEs):
12
+ comments = "".join([random.choice(e) for e in cEs])
13
+ print(comments)
14
+
15
+ commentsElements = [["昨日は","今日は","明日は"],["晴れ","雨","曇り"],["!","です","ですよ"]]
16
+ randomcomment(commentsElements)
17
+ randomcomment(commentsElements)
18
+
19
+ commentsElements2 = [["昨日","今日","明日","明後日"],["は","も"],["晴れ","雨","曇り"],["!","です","ですよ","だね"]]
20
+ randomcomment(commentsElements2)
21
+ randomcomment(commentsElements2)
22
+ randomcomment(commentsElements2)
23
+ ```
24
+ 実行すると以下のようになります。
25
+ ```python
26
+ >>> import random
27
+ >>>
28
+ >>> def randomcomment(cEs):
29
+ ... comments = "".join([random.choice(e) for e in cEs])
30
+ ... print(comments)
31
+ ...
32
+ >>> commentsElements = [["昨日は","今日は","明日は"],["晴れ","雨","曇り"],["!","です","ですよ"]]
33
+ >>> randomcomment(commentsElements)
34
+ 昨日は晴れ!
35
+ >>> randomcomment(commentsElements)
36
+ 昨日は曇りですよ
37
+ >>>
38
+ >>> commentsElements2 = [["昨日","今日","明日","明後日"],["は","も"],["晴れ","雨","曇り"],["!","です","ですよ","だね"]]
39
+ >>> randomcomment(commentsElements2)
40
+ 今日は雨!
41
+ >>> randomcomment(commentsElements2)
42
+ 明日も曇りですよ
43
+ >>> randomcomment(commentsElements2)
44
+ 昨日は曇りです
45
+ ```