Create a gist now

Instantly share code, notes, and snippets.

Embed
World Cup in six lines of Python 3. Jogos da Copa do Mundo em seis linhas de Python 3.
import requests
jogos = requests.get('http://worldcup.sfg.io/matches').json()
for jogo in jogos:
if jogo['status'] in ('completed', 'in progress'):
print (jogo['home_team']['country'], jogo['home_team']['goals'], 'x',
jogo['away_team']['country'], jogo['away_team']['goals'])
@Rynaro

This comment has been minimized.

Show comment
Hide comment
@Rynaro

Rynaro Jun 18, 2014

Amazing! :)

Rynaro commented Jun 18, 2014

Amazing! :)

@eduardo-matos

This comment has been minimized.

Show comment
Hide comment
@eduardo-matos

eduardo-matos Jun 18, 2014

Isn't it request.urlopen instead of urllib.request.urlopen?

Isn't it request.urlopen instead of urllib.request.urlopen?

@linuxsoares

This comment has been minimized.

Show comment
Hide comment
@linuxsoares

linuxsoares Jun 18, 2014

Eu mudei um pouco o Script por causa do request.urlopen.

! /usr/bin/env python

import urllib2
import json
resp = urllib2.urlopen('http://worldcup.sfg.io/matches').read()
for jogo in json.loads(resp.decode('utf-8')):
if jogo['status'] == 'completed':
print (jogo['home_team']['country'], jogo['home_team']['goals'], 'x', jogo['away_team']['country'], jogo['away_team']['goals'])

Eu mudei um pouco o Script por causa do request.urlopen.

! /usr/bin/env python

import urllib2
import json
resp = urllib2.urlopen('http://worldcup.sfg.io/matches').read()
for jogo in json.loads(resp.decode('utf-8')):
if jogo['status'] == 'completed':
print (jogo['home_team']['country'], jogo['home_team']['goals'], 'x', jogo['away_team']['country'], jogo['away_team']['goals'])

@itjp

This comment has been minimized.

Show comment
Hide comment
@itjp

itjp Jun 19, 2014

Nao funciona em Python 2.x ????

itjp commented Jun 19, 2014

Nao funciona em Python 2.x ????

@kanazux

This comment has been minimized.

Show comment
Hide comment
@kanazux

kanazux Jun 19, 2014

@itjp
da sim
from urllib2 import urlopen
import json
[jogo for jogo in json.loads(fd.decode('utf-8')) if jogo['status'] == 'completed']

Python 2.7.3 (default, Mar 13 2014, 11:03:55)

vlw professor ;)

kanazux commented Jun 19, 2014

@itjp
da sim
from urllib2 import urlopen
import json
[jogo for jogo in json.loads(fd.decode('utf-8')) if jogo['status'] == 'completed']

Python 2.7.3 (default, Mar 13 2014, 11:03:55)

vlw professor ;)

@MB6

This comment has been minimized.

Show comment
Hide comment
@MB6

MB6 Jun 19, 2014

@itjp
esto funciona en python 2.7 si tiene Requests, si no, hace pip install requests

import requests
resp = requests.get('http://worldcup.sfg.io/matches')
for jogo in resp.json():
if jogo['status'] == 'completed':
print jogo['home_team']['country'], jogo['home_team']['goals'], 'x', jogo['away_team']['country'], jogo['away_team']['goals']

MB6 commented Jun 19, 2014

@itjp
esto funciona en python 2.7 si tiene Requests, si no, hace pip install requests

import requests
resp = requests.get('http://worldcup.sfg.io/matches')
for jogo in resp.json():
if jogo['status'] == 'completed':
print jogo['home_team']['country'], jogo['home_team']['goals'], 'x', jogo['away_team']['country'], jogo['away_team']['goals']

@dhagrow

This comment has been minimized.

Show comment
Hide comment
@dhagrow

dhagrow Jun 19, 2014

from __future__ import unicode_literals
try:
    import requests
except ImportError:
    import json
    try:
        from urllib.request import urlopen
    except ImportError:
        from urllib2 import urlopen
    get = lambda u: json.loads(urlopen(u).read().decode('utf-8'))
else:
    get = lambda u: requests.get(u).json()

data = get('http://worldcup.sfg.io/matches')
width = max(len(x['home_team']['country'])
    for x in data if x['status'] == 'completed')
for jogo in data:
    if jogo['status'] == 'completed':
        home = jogo['home_team']
        away = jogo['away_team']
        print('{:>{}} {} x {} {}'.format(
            home['country'], width, home['goals'],
            away['goals'], away['country']))

I was bored :/

dhagrow commented Jun 19, 2014

from __future__ import unicode_literals
try:
    import requests
except ImportError:
    import json
    try:
        from urllib.request import urlopen
    except ImportError:
        from urllib2 import urlopen
    get = lambda u: json.loads(urlopen(u).read().decode('utf-8'))
else:
    get = lambda u: requests.get(u).json()

data = get('http://worldcup.sfg.io/matches')
width = max(len(x['home_team']['country'])
    for x in data if x['status'] == 'completed')
for jogo in data:
    if jogo['status'] == 'completed':
        home = jogo['home_team']
        away = jogo['away_team']
        print('{:>{}} {} x {} {}'.format(
            home['country'], width, home['goals'],
            away['goals'], away['country']))

I was bored :/

@nadrane

This comment has been minimized.

Show comment
Hide comment
@nadrane

nadrane Jun 19, 2014

you could actually avoid decoding the response as utf-8 by using the requests module (which is an incredible wrapper around the lacking urllib module). It will identify the encoding for you using chardet and will automatically decode response contents.

nadrane commented Jun 19, 2014

you could actually avoid decoding the response as utf-8 by using the requests module (which is an incredible wrapper around the lacking urllib module). It will identify the encoding for you using chardet and will automatically decode response contents.

@MichaelAquilina

This comment has been minimized.

Show comment
Hide comment
@MichaelAquilina

MichaelAquilina Jun 19, 2014

Managed it in 4 lines :)

import requests
req = requests.get('http://worldcup.sfg.io/matches')
for match in [m for m in req.json() if m['status'] == 'completed']:
    print match['home_team']['country'], match['home_team']['goals'], 'v', match['away_team']['country'], match['away_team']['goals'] 

Managed it in 4 lines :)

import requests
req = requests.get('http://worldcup.sfg.io/matches')
for match in [m for m in req.json() if m['status'] == 'completed']:
    print match['home_team']['country'], match['home_team']['goals'], 'v', match['away_team']['country'], match['away_team']['goals'] 
@Duta

This comment has been minimized.

Show comment
Hide comment

Duta commented Jun 19, 2014

@dhagrow Nice!

@beallio

This comment has been minimized.

Show comment
Hide comment
@cagdassalur

This comment has been minimized.

Show comment
Hide comment
@cagdassalur

cagdassalur Jun 19, 2014

1-liner in python2.7 if you don't count imports. Mind the ugliness.

import urllib2, json
print '\n'.join([' '.join((jogo['home_team']['country'], str(jogo['home_team']['goals']), 'x', jogo['away_team']['country'], str(jogo['away_team']['goals']))) for jogo in json.loads(urllib2.urlopen('http://worldcup.sfg.io/matches').read().decode('utf-8')) if jogo['status'] == 'completed'])

1-liner in python2.7 if you don't count imports. Mind the ugliness.

import urllib2, json
print '\n'.join([' '.join((jogo['home_team']['country'], str(jogo['home_team']['goals']), 'x', jogo['away_team']['country'], str(jogo['away_team']['goals']))) for jogo in json.loads(urllib2.urlopen('http://worldcup.sfg.io/matches').read().decode('utf-8')) if jogo['status'] == 'completed'])
@ThaWeatherman

This comment has been minimized.

Show comment
Hide comment
@ThaWeatherman

ThaWeatherman Jun 20, 2014

I like the competition that has started over fewest lines of code

I like the competition that has started over fewest lines of code

@sametmax

This comment has been minimized.

Show comment
Hide comment
@sametmax

sametmax Jun 20, 2014

@ThaWeatherman

Always. If you post a "x lines" titled post, people will try to come up with a shorter version. Wait for the ruby samples to come :)

But let's all remember that in Python, readability is more important than concision. If you want to keep it small, readable and PEP8, you should not try to compress more than :

import json
import urllib.request as req
res = req.urlopen('http://worldcup.sfg.io/matches').read().decode('utf-8')
for m in filter(lambda d: d['status'] == 'completed', json.loads(res)):
   template = "{h[country]} {h[goals]} x {a[country]} {a[goals]}"
   print(template.format(h=m['home_team'], a=m['away_team']))

Note the 80 char limits. More lines, but way more readable.

You can always make any Python code fits on one line, either with exec() + and or ;. But what's the point ?

And with requests :

import requests
r = requests.get('http://worldcup.sfg.io/matches').json()
m = ((m['home_team'], m['away_team']) for m in r if m['status'] == 'completed')
for h, a in m: 
   print(h['country'], h['goals'], 'x', a['country'], a['goals'])

And even like that, it's rather add some lines to have decent variables names.

Otherwise, it's not Python code, anymore, it's perl.

@ThaWeatherman

Always. If you post a "x lines" titled post, people will try to come up with a shorter version. Wait for the ruby samples to come :)

But let's all remember that in Python, readability is more important than concision. If you want to keep it small, readable and PEP8, you should not try to compress more than :

import json
import urllib.request as req
res = req.urlopen('http://worldcup.sfg.io/matches').read().decode('utf-8')
for m in filter(lambda d: d['status'] == 'completed', json.loads(res)):
   template = "{h[country]} {h[goals]} x {a[country]} {a[goals]}"
   print(template.format(h=m['home_team'], a=m['away_team']))

Note the 80 char limits. More lines, but way more readable.

You can always make any Python code fits on one line, either with exec() + and or ;. But what's the point ?

And with requests :

import requests
r = requests.get('http://worldcup.sfg.io/matches').json()
m = ((m['home_team'], m['away_team']) for m in r if m['status'] == 'completed')
for h, a in m: 
   print(h['country'], h['goals'], 'x', a['country'], a['goals'])

And even like that, it's rather add some lines to have decent variables names.

Otherwise, it's not Python code, anymore, it's perl.

@XenGi

This comment has been minimized.

Show comment
Hide comment
@XenGi

XenGi Jun 20, 2014

Here's my take on the world cup:

if worldcup:
    pass

But nice code anyways. ;)

XenGi commented Jun 20, 2014

Here's my take on the world cup:

if worldcup:
    pass

But nice code anyways. ;)

@kennyledet

This comment has been minimized.

Show comment
Hide comment

^ Lmao

@amferraz

This comment has been minimized.

Show comment
Hide comment
@amferraz

amferraz Jun 20, 2014

World cup in six lines. Wait, six lines? Brazil confirmed!

World cup in six lines. Wait, six lines? Brazil confirmed!

@fmasanori

This comment has been minimized.

Show comment
Hide comment
Owner

fmasanori commented Jun 20, 2014

@XenGi cool code

@fmasanori

This comment has been minimized.

Show comment
Hide comment
@fmasanori

fmasanori Jun 20, 2014

@dhagrow Marvin hitchhiker's guide to the galaxy "I was bored :/"

Owner

fmasanori commented Jun 20, 2014

@dhagrow Marvin hitchhiker's guide to the galaxy "I was bored :/"

@natorsc

This comment has been minimized.

Show comment
Hide comment
@natorsc

natorsc Jun 21, 2014

alunos do Python para zumbis na área akkakakaka.


from urllib import request
import json

resp = request.urlopen('http://worldcup.sfg.io/matches').read()
for jogo in json.loads(resp.decode('utf-8')):
if jogo['status'] == 'completed':
hora = jogo['datetime']
print (jogo['location'],(hora[0:10], hora[11:16]))
print ("Vencedor:", jogo['winner'])
print (jogo['home_team']['country'], jogo['home_team']['goals'], 'x', jogo['away_team']['country'], jogo['away_team']['goals'],"\n")

sair = str(input("Precione ENTER para sair"))

natorsc commented Jun 21, 2014

alunos do Python para zumbis na área akkakakaka.


from urllib import request
import json

resp = request.urlopen('http://worldcup.sfg.io/matches').read()
for jogo in json.loads(resp.decode('utf-8')):
if jogo['status'] == 'completed':
hora = jogo['datetime']
print (jogo['location'],(hora[0:10], hora[11:16]))
print ("Vencedor:", jogo['winner'])
print (jogo['home_team']['country'], jogo['home_team']['goals'], 'x', jogo['away_team']['country'], jogo['away_team']['goals'],"\n")

sair = str(input("Precione ENTER para sair"))

@willmendesneto

This comment has been minimized.

Show comment
Hide comment

Awesome!

@GuilhermePython

This comment has been minimized.

Show comment
Hide comment
@GuilhermePython

GuilhermePython Jul 8, 2014

No meu Python so rodou assim (dei um espaço na terceira linha):

import urllib.request
import json
resp = urllib.request.urlopen ('http://worldcup.sfg.io/matches').read()
for jogo in json.loads(resp.decode('utf-8')):
if jogo['status'] == 'completed':
print (jogo['home_team']['country'], jogo['home_team']['goals'], 'x', jogo['away_team']['country'], jogo['away_team']['goals'])

No meu Python so rodou assim (dei um espaço na terceira linha):

import urllib.request
import json
resp = urllib.request.urlopen ('http://worldcup.sfg.io/matches').read()
for jogo in json.loads(resp.decode('utf-8')):
if jogo['status'] == 'completed':
print (jogo['home_team']['country'], jogo['home_team']['goals'], 'x', jogo['away_team']['country'], jogo['away_team']['goals'])

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment