473,578 Members | 2,818 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

simple way to un-nest (flatten?) list

djc
There is I am sure an easy way to do this, but I seem to be brain dead
tonight. So:

I have a table such that I can do

[line for line in table if line[7]=='JDOC']
and
[line for line in table if line[7]=='Aslib']
and
[line for line in table if line[7]=='ASLIB']
etc

I also have a dictionary
r= {'a':('ASLIB',' Aslib'),'j':('J DOC', 'jdoc')}
so I can extract values
r.values()
[('ASLIB', 'Aslib'), ('JDOC', 'jdoc')]

I would like to do

[line for line in table if line[7] in ('JDOC','jdoc', 'Aslib','ASLIB' )]

so how should I get from
{'a':('ASLIB',' Aslib'),'j':('J DOC','jdoc')}
to
('Aslib','ASLIB ','JDOC','jdoc' )

--
djc
Nov 5 '06 #1
5 2685
djc wrote:
There is I am sure an easy way to do this, but I seem to be brain dead
tonight. So:

I have a table such that I can do

[line for line in table if line[7]=='JDOC']
and
[line for line in table if line[7]=='Aslib']
and
[line for line in table if line[7]=='ASLIB']
etc

I also have a dictionary
r= {'a':('ASLIB',' Aslib'),'j':('J DOC', 'jdoc')}
so I can extract values
r.values()
[('ASLIB', 'Aslib'), ('JDOC', 'jdoc')]

I would like to do

[line for line in table if line[7] in ('JDOC','jdoc', 'Aslib','ASLIB' )]

so how should I get from
{'a':('ASLIB',' Aslib'),'j':('J DOC','jdoc')}
to
('Aslib','ASLIB ','JDOC','jdoc' )
Meet itertools:

from itertools import chain
names = set(chain(*r.it ervalues()))
print [line for line in table if line[7] in names]
George

Nov 5 '06 #2
On Sun, 05 Nov 2006 21:43:33 +0000, djc wrote:
There is I am sure an easy way to do this, but I seem to be brain dead
tonight. So:

I have a table such that I can do

[line for line in table if line[7]=='JDOC']
and
[line for line in table if line[7]=='Aslib']
and
[line for line in table if line[7]=='ASLIB']
etc

I also have a dictionary
r= {'a':('ASLIB',' Aslib'),'j':('J DOC', 'jdoc')}
so I can extract values
r.values()
[('ASLIB', 'Aslib'), ('JDOC', 'jdoc')]

I would like to do

[line for line in table if line[7] in ('JDOC','jdoc', 'Aslib','ASLIB' )]
What is the purpose of the "if line[7]" bit?
so how should I get from
{'a':('ASLIB',' Aslib'),'j':('J DOC','jdoc')}
to
('Aslib','ASLIB ','JDOC','jdoc' )

Assuming you don't care what order the strings are in:

r = {'a':('ASLIB',' Aslib'),'j':('J DOC','jdoc')}
result = sum(r.values(), ())

If you do care about the order:

r = {'a':('ASLIB',' Aslib'),'j':('J DOC','jdoc')}
keys = r.keys()
keys.sort()
result = []
for key in keys:
result.extend(r[key])
result = tuple(result)
--
Steven.

Nov 6 '06 #3
djc
George Sakkis wrote:
Meet itertools:

from itertools import chain
names = set(chain(*r.it ervalues()))
print [line for line in table if line[7] in names]
Steven D'Aprano wrote:
Assuming you don't care what order the strings are in:

r = {'a':('ASLIB',' Aslib'),'j':('J DOC','jdoc')}
result = sum(r.values(), ())

If you do care about the order:

r = {'a':('ASLIB',' Aslib'),'j':('J DOC','jdoc')}
keys = r.keys()
keys.sort()
result = []
for key in keys:
result.extend(r[key])
result = tuple(result)
Thank you everybody.
As it is possible that the tuples will not always be the same word in
variant cases
result = sum(r.values(), ())
will do fine and is as simple as I suspected the answer would be.

--
djc
Nov 6 '06 #4
djc:
As it is possible that the tuples will not always be the same word in
variant cases
result = sum(r.values(), ())
will do fine and is as simple as I suspected the answer would be.
It is simple, but I suggest you to take a look at the speed of that
part of your code into your program. With this you can see the
difference:

from time import clock
d = dict((i,range(3 00)) for i in xrange(300))

t = clock()
r1 = sum(d.values(), [])
print clock() - t

t = clock()
r2 = []
for v in d.values(): r2.extend(v)
print clock() - t

assert r1 == r2

Bye,
bearophile

Nov 6 '06 #5
djc
be************@ lycos.com wrote:
It is simple, but I suggest you to take a look at the speed of that
part of your code into your program. With this you can see the
difference:

from time import clock
d = dict((i,range(3 00)) for i in xrange(300))

t = clock()
r1 = sum(d.values(), [])
print clock() - t

t = clock()
r2 = []
for v in d.values(): r2.extend(v)
print clock() - t
Yes, interesting, and well worth noting

1 for v in d.values(): r1.extend(v)

2 from itertools import chain
set(chain(*d.it ervalues()))

3 set(v for t in d.values() for v in t)

4 sum(d.values(), [])

5 reduce((lambda l,v: l+v), d.values())

on IBM R60e [CoreDuo 1.6MHz/2GB]
d = dict((i,range(x )) for i in xrange(x))
x t1 t2 t3 t4 t5
300 0.0 0.02 0.04 0.31 0.32
500 0.01 0.09 0.1 1.67 1.69
1000 0.02 0.3 0.4 16.17 16.15
0.03 0.28 0.42 16.37 16.31
1500 0.03 0.76 0.94 57.05 57.13
2000 0.07 1.2 1.66 136.6 136.97
2500 0.11 2.34 2.64 268.44 268.85

but on the other hand, as the intended application is a small command
line app where x is unlikely to reach double figures and there are only
two users, myself included:
d =
{'a':['ASLIB','Aslib'],'j':['JDOC','jdoc'],'x':['test','alt','3 rd'],'y':['single',]}
0.0 0.0 0.0 0.0 0.0

And sum(d.values(), []) has the advantage of raising a TypeError in the
case of a possible mangled input.

{'a':['ASLIB','Aslib'],'j':['JDOC','jdoc'],'x':['test','alt','3 rd'],'y':'single'}
r1
['ASLIB', 'Aslib', 'test', 'alt', '3rd', 'JDOC', 'jdoc', 's', 'i', 'n',
'g', 'l', 'e']
r2
set(['Aslib', 'JDOC', 'g', '3rd', 'i', 'l', 'n', 'ASLIB', 's', 'test',
'jdoc', 'alt', 'e'])
r4 = sum(d.values(), [])
TypeError: can only concatenate list (not "str") to list

--
djc
Nov 8 '06 #6

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

Similar topics

3
24904
by: Kofi | last post by:
I need just the names of tables, views and sprocs within a SQL Server database. What's the easiest way to do this?
10
3043
by: Jason | last post by:
Hi, I have a few million data items being received by my program and I wish to store them in a list, with each item being inserted in any position in the list. Any performance tips so that my program runs ok? I have checked out the STL and have thought of using vector, set, list, deque and map. I dont know how these things are...
2
1921
by: ckroom | last post by:
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Could anybody tell me if this code is right? Thanks. struct lista_alumnos {
9
1322
by: law | last post by:
When I start unselecting in a list box, when I deselect the last one, it produces the following error: Run time error 5, and this is highlighted: strSQL = strSQL & "WHERE tblProduct.Product IN (" & Left(strTemp, Len(strTemp) - 2) & ");" any ideas?
1
1732
by: timmso | last post by:
I am trying to build a simple asp.net project. What sort of control do I need to use to simply display a list of links in a table format? For example, let's say I have a database table: tblNames ID Name 1 Blue 2 Grey 3 Green
4
1954
by: KraftDiner | last post by:
Is there a cleaner way to implement this code? if len(self.listOfObjects) == 0: self.listOfObjects.append(self.currentObject) elif: self.listOfObjects = self.currentObject listOfObjects is a list of lists.... If the listOfObjects is then I have to use append to add the first list
10
1407
by: marcstuart | last post by:
How do I divide a list into a set group of sublist's- if the list is not evenly dividable ? consider this example: x = y = 3 # number of lists I want to break x into z = y/x what I would like to get is 3 sublists
0
840
by: John Machin | last post by:
Guilherme Polo wrote: He didn't need to. He explicitly said "list" (which permits duplicates) and didn't mention a self-imposed uniqueness constraint.
4
1083
by: Chickenman | last post by:
First time poster here so hopefully will not get flamed too badly ;) I am trying to teach myself C# and am using VS2005 right now on XP. Here is the code snippet I have after doing a streamreader: string llarray = line.Split(','); string labelInfo = llarray.ToString() + "-" + llarray.ToString(); string completelabelInfo =...
0
7850
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, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
8126
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. ...
0
8291
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7874
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...
0
8150
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6524
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 project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5664
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...
0
3801
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1114
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...

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.