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

回答編集履歴

2

追記

2021/03/31 03:21

投稿

quickquip
quickquip

スコア11312

answer CHANGED
@@ -20,4 +20,50 @@
20
20
 
21
21
  x_org = ['a', 'b', 'c', 'd']
22
22
  x_list = list(chain.from_iterable(zip(*tee(x_org, 2))))
23
+ ```
24
+
25
+
26
+ ----
27
+ 追記
28
+ ちなみになんですが、質問に書いてあるコードが最速だと思います。
29
+
30
+ ```plain
31
+ In [1]: from itertools import chain, repeat, tee
32
+ ...:
33
+ ...: def a(x_org):
34
+ ...: return [x for x in x_org for _i in range(2)]
35
+ ...:
36
+ ...: def aa(x_org):
37
+ ...: return [y for x in ['a', 'b', 'c', 'd'] for y in [x] * 2]
38
+ ...:
39
+ ...: def b(x_org):
40
+ ...: return list(chain.from_iterable([x] * 2 for x in x_org))
41
+ ...:
42
+ ...: def c(x_org):
43
+ ...: return list(chain.from_iterable(zip(*tee(x_org, 2))))
44
+ ...:
45
+ ...: def d(x_org):
46
+ ...: x_list = []
47
+ ...: for x in x_org:
48
+ ...: x_list.append(x)
49
+ ...: x_list.append(x)
50
+ ...: return x_list
51
+ ...:
52
+
53
+ In [2]: x_org = ['a', 'b', 'c', 'd']
54
+
55
+ In [3]: %timeit a(x_org)
56
+ 1.33 µs ± 44.9 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
57
+
58
+ In [4]: %timeit aa(x_org)
59
+ 991 ns ± 29.4 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
60
+
61
+ In [5]: %timeit b(x_org)
62
+ 1.25 µs ± 5.31 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
63
+
64
+ In [6]: %timeit c(x_org)
65
+ 1.08 µs ± 42.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
66
+
67
+ In [7]: %timeit d(x_org)
68
+ 617 ns ± 25.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
23
69
  ```

1

些細

2021/03/31 03:21

投稿

quickquip
quickquip

スコア11312

answer CHANGED
@@ -14,7 +14,7 @@
14
14
  ```
15
15
 
16
16
 
17
- (3)teeとzipで`['a', 'a'], ['b', 'b'],,,` のシーケンスを作ってflatten
17
+ (3)teeとzipで`('a', 'a'), ('b', 'b'),,,` のシーケンスを作ってflatten
18
18
  ```python
19
19
  from itertools import chain, tee
20
20