简体   繁体   中英

Python - simplifying code with list comprehension

given the playlists:

energy_playlist = [{u'track': u'Nude', u'feature': u'energy', u'value': 0.342, u'artist': u'Radiohead'}, {u'track': u'Kaleidoscope', u'feature': u'energy', u'value': 0.285, u'artist': u'Coldplay'}, {u'track': u'Faust Arp', u'feature': u'energy', u'value': 0.289, u'artist': u'Radiohead'}, {u'track': u'Running Up That Hill', u'feature': u'energy', u'value': 0.356, u'artist': u'Placebo'}, {u'track': u'Codex', u'feature': u'energy', u'value': 0.128, u'artist': u'Radiohead'}, {u'track': u'True Love Waits', u'feature': u'energy', u'value': 0.132, u'artist': u'Radiohead'}, {u'track': u'Asleep - 2011 Remastered Version', u'feature': u'energy', u'value': 0.255, u'artist': u'The Smiths'}, {u'track': u'Glass Eyes', u'feature': u'energy', u'value': 0.11, u'artist': u'Radiohead'}, {u'track': u'Pyramid Song', u'feature': u'energy', u'value': 0.335, u'artist': u'Radiohead'}, {u'track': u'Life On Mars? - 2015 Remastered Version', u'feature': u'energy', u'value': 0.384, u'artist': u'David Bowie'}, {u'track': u'Exit Music (For a Film)', u'feature': u'energy', u'value': 0.276, u'artist': u'Radiohead'}, {u'track': u'Videotape', u'feature': u'energy', u'value': 0.384, u'artist': u'Radiohead'}, {u'track': u'High And Dry', u'feature': u'energy', u'value': 0.383, u'artist': u'Radiohead'}]

and

tempo_playlist = [{u'track': u'Codex', u'feature': u'tempo', u'value': 58.993, u'artist': u'Radiohead'}, {u'track': u'Pyramid Song', u'feature': u'tempo', u'value': 77.078, u'artist': u'Radiohead'}, {u'track': u'Videotape', u'feature': u'tempo', u'value': 77.412, u'artist': u'Radiohead'}]

I can find the matching tracks in this way:

for d1 in energy_playlist:
    for d2 in tempo_playlist:
        if d1['track'] == d2['track']:
            print (d2['track'])

how do I manage to do the same with a list comprehension in one line, assigned to a variable final_playlist ?

Does this help?

energy_tracks = [p["track"] for p in energy_playlist]
tempo_tracks = [p["track"] for p in tempo_playlist]

print set(energy_tracks).intersection(tempo_tracks)

Ok, in one line, you want it now :-D? I would ask why, but just for fun ...

result = set(p["track"] for p in energy_playlist).intersection(p["track"] for p in tempo_playlist)

Actually, this one-liner is maybe a bit faster than the three-liner above, as the lists of tracks are not explicitly saved in memory, but as iterators consumed by the set object.

Here you go:

[x['track'] for x in tempo_playlist if x['track'] in [y['track'] for y in energy_playlist]]

Although I agree with other people cramming in one line is less readable than multiple lines.

将您的整个代码转换为列表理解

final_playlist = [d2['track'] for d1 in energy_playlist for d2 in tempo_playlist if d1['track'] == d2['track']]

Except that a) your code is more readable, so don't see the need of one line, but most importantly b) a one liner cannot improve really the performance :)... Let me demonstrate:

import timeit

energy_playlist = [{u'track': u'Nude', u'feature': u'energy', u'value': 0.342, u'artist': u'Radiohead'}, {u'track': u'Kaleidoscope', u'feature': u'energy', u'value': 0.285, u'artist': u'Coldplay'}, {u'track': u'Faust Arp', u'feature': u'energy', u'value': 0.289, u'artist': u'Radiohead'}, {u'track': u'Running Up That Hill', u'feature': u'energy', u'value': 0.356, u'artist': u'Placebo'}, {u'track': u'Codex', u'feature': u'energy', u'value': 0.128, u'artist': u'Radiohead'}, {u'track': u'True Love Waits', u'feature': u'energy', u'value': 0.132, u'artist': u'Radiohead'}, {u'track': u'Asleep - 2011 Remastered Version', u'feature': u'energy', u'value': 0.255, u'artist': u'The Smiths'}, {u'track': u'Glass Eyes', u'feature': u'energy', u'value': 0.11, u'artist': u'Radiohead'}, {u'track': u'Pyramid Song', u'feature': u'energy', u'value': 0.335, u'artist': u'Radiohead'}, {u'track': u'Life On Mars? - 2015 Remastered Version', u'feature': u'energy', u'value': 0.384, u'artist': u'David Bowie'}, {u'track': u'Exit Music (For a Film)', u'feature': u'energy', u'value': 0.276, u'artist': u'Radiohead'}, {u'track': u'Videotape', u'feature': u'energy', u'value': 0.384, u'artist': u'Radiohead'}, {u'track': u'High And Dry', u'feature': u'energy', u'value': 0.383, u'artist': u'Radiohead'}]
tempo_playlist = [{u'track': u'Codex', u'feature': u'tempo', u'value': 58.993, u'artist': u'Radiohead'}, {u'track': u'Pyramid Song', u'feature': u'tempo', u'value': 77.078, u'artist': u'Radiohead'}, {u'track': u'Videotape', u'feature': u'tempo', u'value': 77.412, u'artist': u'Radiohead'}]

def foo1():
    ret = []
    for d1 in energy_playlist:
        for d2 in tempo_playlist:
            if d1['track'] == d2['track']:
                ret.append(d1["track"])
    return ret

def foo2():
    ret = []
    for d1 in energy_playlist:
        for d2 in tempo_playlist:
            if d1['track'] == d2['track']:
                pass
    return None

def foo3():
    return [d2['track'] for d1 in energy_playlist for d2 in tempo_playlist if d1['track'] == d2['track']]


def bar():
    tempo_tracks = [i["track"] for i in tempo_playlist]
    return [i["track"] for i in energy_playlist if i["track"] in tempo_tracks]

print("foo1:", timeit.timeit(foo1))
print("foo2:", timeit.timeit(foo2))
print("foo3:", timeit.timeit(foo3))
print("bar:", timeit.timeit(bar))

# foo1: 5.550314342981437
# foo2: 5.025758317991858
# foo3: 5.3763819159939885
# bar: 2.86007208598312

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM