0
1

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 3 years have passed since last update.

Python3でのリストの内包表記、ジェネレータ式、タプルのアンパックなど構文メモ

Last updated at Posted at 2020-07-26

##ジェネレータ式でのデカルト積

sample.py
colors_list = ['red','white','blue']
size_lists =  ['S','M','L']
for t_shirts in ('%s %s' % (c, s) for c in colors_list for s in size_lists):
  print (repr(t_shirts))
>'red S'
>'red M'
>'red L'
>'white S'
>'white M'
>'white L'
>'blue S'
>'blue M'
>'blue L'

##リストの内包表記でのデカルト積

sample.py
colors_list = ['red','white','blue']
size_lists =  ['S','M','L']
t_shirts = [(c, s) for c in colors_list for s in size_lists)]
  print (repr(t_shirts))
>[('red', 'S'), ('red', 'M'), ('red', 'L'), ('white', 'S'), ('white', 'M'), ('white', 'L'), ('blue', 'S'), ('blue', 'M'), ('blue', 'L')]

##タプルのアンパック

sample.py
japan_std = (35.00116, 134.59501)
latitude, longitude =  japan_std 
print ("latitude:" + repr(latitude))
print ("longitude:" + repr(longitude))
>latitude:35.00116。。。
>longitude:134.59501

※reprがないと、floatのため例外となってしまう。

##Setリテラルの空集合

sample.py
s = {42.195}  # 1つの要素のみのsetリテラル
print ("s:" + repr(s))
s.pop()
print ("s:" + repr(s))
>s:{42.195}
>s:set()  # 空集合は、set()と表現される

##ディクショナリ内包表記

sample.py
NATIONAL_CODES=[(91,'INDIA'),(55,'BRAZIL'),(1,'UNITED STATES'),(81,'JAPAN'),(86,'CHINA')]
country_code = {country:code for code, country in NATIONAL_CODES}
print("country_code" + repr(country_code ))
>country_code{'INDIA': 91, 'BRAZIL': 55, 'UNITED STATES': 1, 'JAPAN': 81, 'CHINA': 86}

#Python の内部構造の視覚化ツール
Python Tutor

0
1
1

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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?