473,656 Members | 2,756 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Dict Comprehension ?

Given 2 Number-Lists say l0 and l1,
count the various positiv differences between the 2 lists

the following part works:

dif=[abs(x-y) for x in l0 for y in l1]
da={}
for d in dif: da[d]=da.get(d,0)+1

i wonder, if there is a way, to avoid the list dif

Ernst-Ludwig Brust
Oct 6 '08 #1
6 2724
Ernst-Ludwig Brust:
Given 2 Number-Lists say l0 and l1,
count the various positiv differences between the 2 lists
...
i wonder, if there is a way, to avoid the list dif
Instead of creating the list (array) dif, you can create a lazy
iterator. Then you can fed it to a set.

Bye,
bearophile
Oct 6 '08 #2
On Oct 6, 8:59 am, "Ernst-Ludwig Brust" <seinnix...@onl ine.dewrote:
Given 2 Number-Lists say l0 and l1,
count the various positiv differences between the 2 lists

the following part works:

dif=[abs(x-y) for x in l0 for y in l1]
da={}
for d in dif: da[d]=da.get(d,0)+1

i wonder, if there is a way, to avoid the list dif

Ernst-Ludwig Brust
from collections import defaultdict
da=defaultdict( int)
for x in [10]:
for y in [11]:
da[abs(x-y)]+=1
Oct 6 '08 #3
"Ernst-Ludwig Brust" <se********@onl ine.dewrites:
Given 2 Number-Lists say l0 and l1,
count the various positiv differences between the 2 lists

the following part works:

dif=[abs(x-y) for x in l0 for y in l1]
da={}
for d in dif: da[d]=da.get(d,0)+1

i wonder, if there is a way, to avoid the list dif
You can iterate over any iterable. A generator is iterable; and you
can (among other ways) create a generator with a generator
expression.

Fortunately, you already know how to write any generator expression:
it's the same as a list comprehension, but without the square
brackets.

So, instead of making a list of differences and iterating over it::
>>seq_a = [15, 17, 26]
seq_b = [14, 17, 22]
diffs = [abs(a - b) for a in seq_a for b in seq_b]
diff_accumula tor = {}
for diff in diffs:
... diff_accumulato r[diff] = diff_accumulato r.get(diff, 0) + 1
...
>>diff_accumula tor
{0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 7: 1, 9: 1, 12: 1}

you can skip the intermediate list creation and iterate over the
generator made by an identical generator expression::
>>seq_a = [15, 17, 26]
seq_b = [14, 17, 22]
diff_accumula tor = {}
for diff in (abs(a - b) for a in seq_a for b in seq_b):
... diff_accumulato r[diff] = diff_accumulato r.get(diff, 0) + 1
...
>>diff_accumula tor
{0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 7: 1, 9: 1, 12: 1}

If you wanted to avoid starting the dict empty and writing the ‘for’
loop yourself, you could even create your dict from a generator (the
dict type can make a new dict from any key+value iterable) with the
help of the standard library ‘itertools’ module::
>>import itertools
seq_a = [15, 17, 26]
seq_b = [14, 17, 22]
diffs = [abs(a - b) for a in seq_a for b in seq_b]
diff_accumula tor = dict(
... (diff, len(list(items) ))
... for (diff, items) in itertools.group by(diffs)
... )
>>diff_accumula tor
{0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 7: 1, 9: 1, 12: 1}

This also, of course, benefits from the earlier approach to iterate
over the diffs directly instead of an intermediate list::
>>import itertools
seq_a = [15, 17, 26]
seq_b = [14, 17, 22]
diff_accumula tor = dict(
... (diff, len(list(items) ))
... for (diff, items) in itertools.group by(
... abs(a - b) for a in seq_a for b in seq_b
... )
... )
>>diff_accumula tor
{0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 7: 1, 9: 1, 12: 1}

So, generator expressions can be a powerful way to clarify the purpose
of a section of code. They can be over-used, though: don't use them
unless they actually *do* clarify the code; sometimes an explicit
looping construct is clearer.

--
\ “Like the creators of sitcoms or junk food or package tours, |
`\ Java's designers were consciously designing a product for |
_o__) people not as smart as them.” —Paul Graham |
Ben Finney
Oct 7 '08 #4
<be************ @lycos.comschri eb im Newsbeitrag
news:5b******** *************** ***********@m74 g2000hsh.google groups.com...
>
Instead of creating the list (array) dif, you can create a lazy
iterator. Then you can fed it to a set.
Thangs,
this idea is not only less storage-consuming but even faster
than the "List-Version".
But, i used the idea of pruebauno,
as this is faster.

Ernst-Ludwig Brust
Oct 7 '08 #5
"Ben Finney" <bi************ ****@benfinney. id.auschrieb im Newsbeitrag
news:87******** ****@benfinney. id.au...
"Ernst-Ludwig Brust" <se********@onl ine.dewrites:

So, generator expressions can be a powerful way to clarify the purpose
of a section of code. They can be over-used, though: don't use them
unless they actually *do* clarify the code; sometimes an explicit
looping construct is clearer.
Thangs,
my opinion was, that "one-statement-constructions" are
much faster then f.e. explicit loops.
But,
now i know, with Python, this is not allways true.

Ernst-Ludwig Brust
Oct 7 '08 #6
<pr*******@lati nmail.comschrie b im Newsbeitrag
news:7c******** *************** ***********@75g 2000hso.googleg roups.com...
>
from collections import defaultdict
da=defaultdict( int)
for x in [10]:
for y in [11]:
da[abs(x-y)]+=1
Thangs,
collections are a real good idea.
I will use this version.

Ernsst-Ludwwig Brust
Oct 7 '08 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

11
3265
by: Xavier | last post by:
Greetings, (do excuse the possibly comical subject text) I need advice on how I can convert a text db into a dict. Here is an example of what I need done. some example data lines in the text db goes as follows: CODE1!DATA1 DATA2, DATA3
9
12232
by: Robin Cull | last post by:
Imagine I have a dict looking something like this: myDict = {"key 1": , "key 2": , "key 3": , "key 4": } That is, a set of keys which have a variable length list of associated values after them. What I want to do is filter out a subset of this dict to produce another dict that satisfies a set of criteria (in this case whether it contains all four values) to end up with something
7
3094
by: Marcio Rosa da Silva | last post by:
Hi! In dictionaries, unlinke lists, it doesn't matter the order one inserts the contents, elements are stored using its own rules. Ex: >>> d = {3: 4, 1: 2} >>> d {1: 2, 3: 4}
7
1677
by: George Young | last post by:
I am puzzled that creating large dicts with an explicit iterable of key,value pairs seems to be slow. I thought to save time by doing: palettes = dict((w,set(w)) for w in words) instead of: palettes={} for w in words: palettes=set(w)
2
1209
by: Gerardo Herzig | last post by:
Hi all: I have this list thing as a result of a db.query: (short version) result = and so on...what i need to do is some list comprehension that returns me something like result = }, { 'service_id' : 2, 'values':
4
3012
by: bearophileHUGS | last post by:
I have started doing practice creating C extensions for CPython, so here are two ideas I have had, possibly useless. If you keep adding elements to a CPython dict/set, it periodically rebuilds itself. So maybe dict.reserve(n) and a set.reserve(n) methods may help, reserving enough (empty) memory for about n *distinct* keys the programmer wants to add to the dict/set in a short future. I have seen that the the C API of the dicts doesn't...
14
1563
by: Ben | last post by:
I have recently learned how list comprehension works and am finding it extremely cool. I am worried, however, that I may be stuffing it into places that it does not belong. What's the most "pythony" way to do this: even = for x in range(0,width,2): for y in range(0,height,2): color = im.getpixel((x,y))
14
28291
by: erikcw | last post by:
Hi, I'm trying to turn o list of objects into a dictionary using a list comprehension. Something like entries = {} = d.id] for d in links]
22
2083
by: mrkafk | last post by:
Hello everyone, I have written this small utility function for transforming legacy file to Python dict: def lookupdmo(domain): lines = open('/etc/virtual/domainowners','r').readlines() lines = for x in lines]
0
8382
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look ! Part I. Meaning of...
0
8816
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8498
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7311
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development projectplanning, coding, testing, and deploymentwithout human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6162
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupr who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4150
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4300
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2726
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1600
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.