473,698 Members | 1,952 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Further adventures in array slicing.

This is more for my education and not so much for practicality.

I have a structure that sort of looks like this:

mdict = {33:{'name': 'Hello0',
'fields':'field s0',
'valid': 'valid0'
55:{'name': 'Hello1',
'fields':'field s1',
'valid': 'valid1'},
14:{'name': 'Hello2',
'fields':'field s2',
'valid': 'valid2'}}

i.e, each element of the dictionary is itself a dictionary with three
common keys.

I need to unpack this into three seperate arrays called name, fields,
valid. The old code looked like this:

names = []; fields = []; valid = []
for ii in mdict:
names.append(md ict[ii]['name'])
fields.append(m dict[ii]['fields'])
valid.append(md ict[ii]['valid'])

I tried this (to see if it would work) and it seems to work just fine:

def u2(m):
aa = [ms[ii][jj] for jj in 'name','fields' ,'valid' for ii in m]
return tuple(zip(aa[0::3], aa[1::3], aa[2::3]))
names,fields,va lid = u2(mdict)

I was very pleased with myself, except that the real world example of
'fields' and 'valid' is that they can be (but not always) a sequence.
e.g.,

mdefs = {0:{'name': 'Hello0',
'fields':(('Add ress', 8),
('Control', 8)),
'valid': {'Address': (1,255),
'Control': (33,44)}},
1:{'name': 'Hello1',
'fields':'field s1',
'valid': 'valid1'},
2:{'name': 'Hello2',
'fields':'field s2',
'valid': 'valid2'}}

Is there a way to do this with possibly a more concise technique than the
first for loop above?

A second question is: When can you use += vs .append(). Are the two always
the same?

Thanks. :-)

--
Time flies like the wind. Fruit flies like a banana. Stranger things have .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
May 4 '07 #1
3 1191
On May 5, 7:03 am, "Steven W. Orr" <ste...@syslang .netwrote:
This is more for my education and not so much for practicality.
[snip]
>
A second question is: When can you use += vs .append(). Are the two always
the same?
Formally, they can never be the same. They can be used to produce the
same result, in limited circumstances, e.g. these:
alist += bseq
and
alist.append(an element)
will give the same result if bseq == [anelement]

You can use alist.extend(bs eq) instead of alist += bseq

I suggest that you
(a) read the manual sections on each of the 3 possibilities
(b) explore their behaviours at the Python interactive prompt

May 4 '07 #2
A second question is: When can you use += vs .append().
Are the two always the same?
They are never the same unless you only add one item to the list.
append() will only increase the length of a list by 1.

la = [1,2]
lb = [3, 4, 5]
la += lb
print la

lc = [1,2]
lc.append(lb)
print lc

--output:--
[1, 2, 3, 4, 5]
[1, 2, [3, 4, 5]]
print la[2]
print lc[2]

--output:--
3
[3, 4, 5]

May 4 '07 #3
Steven W. Orr <st****@syslang .netwrote:
...
I need to unpack this into three seperate arrays called name, fields,
valid. The old code looked like this:
You're using lists, not arrays. If you DID want arrays, you'd have to
import standard library module array, and you'd be limited to a few
elementary types as items; it's pretty obvious that this is not what you
want -- nevertheless, why use the wrong name?
names = []; fields = []; valid = []
for ii in mdict:
names.append(md ict[ii]['name'])
fields.append(m dict[ii]['fields'])
valid.append(md ict[ii]['valid'])
The order of keys in dictionary mdict is totally arbitrary, therefore
the order of items in those lists is going to be equally arbitrary; you
sure you _want_ that? Normally order IS significant in lists.
I was very pleased with myself, except that the real world example of
'fields' and 'valid' is that they can be (but not always) a sequence.
Why would that make any difference at all?
e.g.,

mdefs = {0:{'name': 'Hello0',
'fields':(('Add ress', 8),
('Control', 8)),
'valid': {'Address': (1,255),
'Control': (33,44)}},
1:{'name': 'Hello1',
'fields':'field s1',
'valid': 'valid1'},
2:{'name': 'Hello2',
'fields':'field s2',
'valid': 'valid2'}}

Is there a way to do this with possibly a more concise technique than the
first for loop above?
not by much:

names = [v['name'] for v in mdict.itervalue s()]
fields = [v['fields'] for v in mdict.itervalue s()]
valid = [v['valid'] for v in mdict.itervalue s()]

but this just saves a few characters, if that.
Alex
May 5 '07 #4

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

Similar topics

1
1877
by: beliavsky | last post by:
Suppose I define a trivial class composed of x and y coordinates and create a Numeric array of instances of that class. class xy: def __init__(self,x=0.0,y=0.0): self.x = x self.y = y def __repr__(self): return ("%6.2f" % self.x) + (",%6.2f" % self.y)
7
8316
by: LutherRevisited | last post by:
I'm wanting to do something with a list that is basically a 2 dimensional array. I'm not so good with lists so can someone give me an example of how I might implement this in Python? thanks.
2
1603
by: Yun Mao | last post by:
Hi python gurus, I have some questions when I'm using python numeric: 1. When I do v = u, it seems u and v still point to the same memory. e.g. When I do v=0, u will be zero out as well. What's the right way to duplicate an array? Now I have to do v = dot(u, identity(N)), which is kind of silly. 2. Is there a way to do Matlab style slicing? e.g. if I have i = array()
10
3763
by: amparikh | last post by:
Ok, my question is not about Virtual destructors and why, but more on the significance. Generally we have a virtual destructor in the base class ( and inadvertently in the derived class) so that you can delete a derived-class object via a base-class pointer...So, the correct destructor(s) gets invoked(the derived class one in particular) and the correct amount of memory is also released. But if the above is true, why isnt it a good...
0
8598
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9152
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...
0
9014
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8855
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6515
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
4358
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...
1
3037
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
2320
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
1995
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.