専門ユニット2/山内研セミナー(2020/10/14)

関連サイトと資料

サンプルプログラム

sample1.py
 
sk = {}
sk['age'] = 150
print(sk)
  
if 'ages' in sk:
  print('存在します!')
else:
  print('存在しません!')
    

sample2.py
 
sk = {'first_name': 'shinji', 'family_name': 'kawasaki', 'weight': 80}
for item in sk:
  print(item, sk[item])
   
print('---------------------------')
for key, value in sk.items():
  print(key, value)
   
print('---------------------------')
for k in sk.keys():
  print(k, sk[k])
   
print('---------------------------')
for v in sk.values():
  print(v)
    

sample3.py
 
page_data = {
  'https://www.atmarkit.co.jp/ait/articles/1906/14/news015.html':
  {
    'author': 'かわさき しんじ',
    'title': 'タプル',
    'pv': 123456
  },
  'https://www.atmarkit.co.jp/ait/articles/1906/13/news021.html':
  {
    'author': '一色 政彦',
    'title': 'Deep Learningコミュニティー……',
    'pv': 123456789
  },
  'https://www.atmarkit.co.jp/ait/articles/1906/04/news009.html':
  {
    'author': 'かわさき しんじ',
    'title': 'リストの操作',
    'pv': 1234567
  }
}
   
pv = 0
for key, value in page_data.items():
  if value['pv'] > pv:
    top_article = value
    top_article_url = key
    pv = value['pv']
   
print(f'top article is {top_article["title"]}')
print(f'top author is {top_article["author"]}')
print(f'top page view is {top_article["pv"]}')
print(f'top article url: {top_article_url}')
    

sample4.py
 
users = [
  { "id": 0, "name": "Hero" },
  { "id": 1, "name": "Dunn" },
  { "id": 2, "name": "Sue" },
  { "id": 3, "name": "Chi" },
  { "id": 4, "name": "Thor" },
  { "id": 5, "name": "Clive" },
  { "id": 6, "name": "Hicks" },
  { "id": 7, "name": "Devin" },
  { "id": 8, "name": "Kate" },
  { "id": 9, "name": "Klein" },
]
   
friendship_pairs = [(0, 1), (0, 2), (1, 2), (1, 3), (2, 3), (3, 4),
  (4, 5), (5, 6), (5, 7), (6, 8), (7, 8), (8, 9)]

friendships = {user["id"]: [] for user in users}
  
print(friendships)
  
for i, j in friendship_pairs:
  friendships[i].append(j)
  friendships[j].append(i)
     
print(friendships)
    

1.3.1 キーコネクタを探せ

test1.py(交友関係の辞書を作成)
users = [
  { "id": 0, "name": "Hero" },
  { "id": 1, "name": "Dunn" },
  { "id": 2, "name": "Sue" },
  { "id": 3, "name": "Chi" },
  { "id": 4, "name": "Thor" },
  { "id": 5, "name": "Clive" },
  { "id": 6, "name": "Hicks" },
  { "id": 7, "name": "Devin" },
  { "id": 8, "name": "Kate" },
  { "id": 9, "name": "Klein" },
]
   
friendship_pairs = [(0, 1), (0, 2), (1, 2), (1, 3), (2, 3), (3, 4),
    (4, 5), (5, 6), (5, 7), (6, 8), (7, 8), (8, 9)]
   
# 各ユーザごとに空のリストで辞書を初期化する
friendships = {user["id"]: [] for user in users}
    
# すべての交友関係をループして、辞書を埋める
for i, j in friendship_pairs:
  friendships[i].append(j)
  friendships[j].append(i)
   
print(friendships)