1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

python zip関数による並列化

Last updated at Posted at 2019-11-23

zipによる並列処理

a.py
num_list = [1, 2, 3]
drink_list = ['water', 'coffee', 'milk']
programingu_language_list = ['python', 'Javascript', 'Java']

# 直列処理
for item1, item2, item3 in drink_list, programingu_language_list:
    print(item1, item2, item3 )

# 並列処理
for item1, item2, item3 in zip(num_list, drink_list, programingu_language_list):
    print(item1, item2, item3 )
直列処理
1 2 3
water coffee milk
python Javascript Java
並列処理
1 water python
2 coffee Javascript
3 milk Java

処理流れ

for item1, item2, item3 in A, B , C

とする。
このときに出力は、以下のようになる。

print(item1, item2, item3)
  • 直列処理
item1 item2 item3
A[0] A[1] A[2]
B[0] B[1] B[2]
C[0] C[1] C[2]
  • 並列処理
item1 item2 item3
A[0] B[0] C[0]
A[1] B[1] C[1]
A[2] B[2] C[2]

zip化したものをリストor タプルへ

a.py
days_en = 'Moday', 'Tuesday', 'Webnesday'
foods = 'curry', 'udon', 'pasta'
print(list(zip(days_en, foods)))
print(dict(zip(days_en, foods)))
結果
[('Moday', 'curry'), ('Tuesday', 'udon'), ('Webnesday', 'pasta')]
{'Moday': 'curry', 'Tuesday': 'udon', 'Webnesday': 'pasta'}

注意

記事とは、関係ないけど、以下のdays_en, foodsとtmpでは結果が変わるんですね。

a.py
days_en = 'Moday', 'Tuesday', 'Webnesday'
foods = 'curry', 'udon', 'pasta'
tmp = days_en, foods
print(tmp)
print(days_en, foods)
```

```python:結果
('Moday', 'Tuesday', 'Webnesday') ('curry', 'udon', 'pasta')
(('Moday', 'Tuesday', 'Webnesday'), ('curry', 'udon', 'pasta'))
```

だから

```python:a.py
days_en = 'Moday', 'Tuesday', 'Webnesday'
foods = 'curry', 'udon', 'pasta'
tmp = days_en, foods
print(tmp)
print(list(zip_tmp))
print(dict(zip_tmp))
```

とやると結果がおかしくなる

```python:結果
(('Moday', 'Tuesday', 'Webnesday'), ('curry', 'udon', 'pasta'))
[(('Moday', 'Tuesday', 'Webnesday'),), (('curry', 'udon', 'pasta'),)]
Traceback (most recent call last):
  File "b.py", line 93, in <module>
    print(dict(zip(tmp)))
ValueError: dictionary update sequence element #0 has length 1; 2 is required
```

以下の代入によって結果がかわる原因について今後調査します

```
tmp = days_en, foods
```

# 参考文献
入門 Python3(:Bill Lubanovic)
1
0
4

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?