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

回答編集履歴

2

追記

2018/03/29 14:37

投稿

LouiS0616
LouiS0616

スコア35678

answer CHANGED
@@ -16,4 +16,22 @@
16
16
  **実行結果** [Wandbox](https://wandbox.org/permlink/d4yBWbZMijSWLhAK)
17
17
  ```
18
18
  {1: ['東京', '神奈川', '千葉'], 2: ['群馬', '茨城', '山梨'], 3: ['長野', '栃木'], 4: ['愛知']}
19
+ ```
20
+
21
+ 追記
22
+ ---
23
+ もしキーが『数値』ではなく『数字』なら。[Wandbox](https://wandbox.org/permlink/0y83iuDNqbBxvKjN)
24
+ ```Python
25
+ lists = ['1', '東京', '神奈川', '千葉', '2', '群馬', '茨城', '山梨', '3', '長野', '栃木', '4', '愛知']
26
+
27
+ dst = {}
28
+ for elem in lists:
29
+ try:
30
+ elem = int(elem)
31
+ dst[elem] = []
32
+ pre_key = elem
33
+ except ValueError:
34
+ dst[pre_key].append(elem)
35
+
36
+ print(dst)
19
37
  ```

1

追記

2018/03/29 14:37

投稿

LouiS0616
LouiS0616

スコア35678

answer CHANGED
@@ -2,20 +2,18 @@
2
2
  ```Python
3
3
  lists = [1, '東京', '神奈川', '千葉', 2, '群馬', '茨城', '山梨', 3, '長野', '栃木', 4, '愛知']
4
4
 
5
- keys = []
5
+ dst = {}
6
- values = []
7
6
  for elem in lists:
8
7
  if isinstance(elem, int):
8
+ dst[elem] = []
9
- keys.append(elem)
9
+ pre_key = elem
10
- values.append([])
11
10
  else:
12
- values[-1].append(elem)
11
+ dst[pre_key].append(elem)
13
12
 
14
- dst = dict(zip(keys, values))
15
13
  print(dst)
16
14
  ```
17
15
 
18
- **実行結果** [Wandbox](https://wandbox.org/permlink/blW3OQWSpflYlodH)
16
+ **実行結果** [Wandbox](https://wandbox.org/permlink/d4yBWbZMijSWLhAK)
19
17
  ```
20
18
  {1: ['東京', '神奈川', '千葉'], 2: ['群馬', '茨城', '山梨'], 3: ['長野', '栃木'], 4: ['愛知']}
21
19
  ```