LoginSignup
1
2

More than 3 years have passed since last update.

はじめてのリスト内包表記

Posted at

課題

# この入力に対して
service = {'Yahoo!': 'www.yahoo.co.jp', 'Google': "www.google.com", 'MSN': 'www.msn.com', 'wiki': 'ja.wikipedia.org'}

# この結果を得たいとする
# www_urls = 'www.yahoo.co.jp,www.google.com,www.msn.com,'
# other_urls  = 'ja.wikipedia.org'

ベタ書き

    www_urls = ''
    other_urls = ''
    for service_name in service:
        url = service[service_name]
        if 'www' in url:
            www_urls = www_urls + url + ','
        else:
            other_urls = other_urls + url + ','
    www_urls = www_urls[:-1]
    other_urls = other_urls[:-1]

    print(www_urls)
    print(other_urls)

カッコワルイ

リスト内法表記

    www_urls_list = [service[service_name] for service_name in service if 'www' in service[service_name]]
    other_urls_list = [service[service_name] for service_name in service if 'www' not in service[service_name]]
    www_urls = ','.join(www_urls_list)
    other_urls = ','.join(other_urls_list)

    print(www_urls)
    print(other_urls)

さらにまとめて

    www_urls = ','.join([service[service_name] for service_name in service if 'www' in service[service_name]])
    other_urls = ','.join([service[service_name] for service_name in service if 'www' not in service[service_name]])

    print(www_urls)
    print(other_urls)
1
2
0

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
2