Howdie Python folks! I am very new to Python ( 3rd day now ) and it has
already earned its place as my fav. language to work in. I hope to
continue, and I really would appreciate some good resources if anybody
would care to contribute.
My current head-scratcher concerns something I can do in Perl which I
would like to have duplicated for Python. I have noticed that it is not
possible to increment an unset value in Python, so I would like to know
how to duplicate the following bit of code using Python dictionaries.
#!/usr/bin/perl
# Parse comma delimited lines and create a final frequency hash
# Real example would read a file line by line
my %dict = {};
my @lines = ( "1,2,3,4,5", "2,3,4,5", "3,4,5", "4,5", "5" );
foreach(@lines) { map( $dict{ $_ }++, split( "," ) ); }
foreach( sort byKeys keys %dict ) {
print "Key: $_\tFrequency: ", "*" x $dict{ $_ }, "\n"
if $dict{ $_ } =~ /\d+/g;
}
sub byKeys { $dict{$b} <=> $dict{$a} }
__DATA__
Results:
Key: 5 Frequency: *****
Key: 4 Frequency: ****
Key: 3 Frequency: ***
Key: 2 Frequency: **
Key: 1 Frequency: *
--
Koncept <<
"The snake that cannot shed its skin perishes. So do the spirits who are
prevented from changing their opinions; they cease to be a spirit." -Nietzsche 5 1297
Koncept wrote: #!/usr/bin/perl
# Parse comma delimited lines and create a final frequency hash # Real example would read a file line by line my %dict = {}; my @lines = ( "1,2,3,4,5", "2,3,4,5", "3,4,5", "4,5", "5" ); foreach(@lines) { map( $dict{ $_ }++, split( "," ) ); } foreach( sort byKeys keys %dict ) { print "Key: $_\tFrequency: ", "*" x $dict{ $_ }, "\n" if $dict{ $_ } =~ /\d+/g; } sub byKeys { $dict{$b} <=> $dict{$a} }
__DATA__ Results: Key: 5 Frequency: ***** Key: 4 Frequency: **** Key: 3 Frequency: *** Key: 2 Frequency: ** Key: 1 Frequency: *
I don't speak Perl, but based on your output, I'd probably do something
like:
py> lines = ["1,2,3,4,5", "2,3,4,5", "3,4,5", "4,5", "5"]
py> counts = {}
py> for items in lines:
.... for item in items.split(','):
.... counts[item] = counts.get(item, 0) + 1
....
py> for key in sorted(counts, key=counts.__getitem__, reverse=True):
.... print 'Key: %s Frequency: %s' % (key, '*'*counts[key])
....
Key: 5 Frequency: *****
Key: 4 Frequency: ****
Key: 3 Frequency: ***
Key: 2 Frequency: **
Key: 1 Frequency: *
I'm probably missing a few subtleties, but hopefully this will get you
started.
STeVe
Koncept wrote: Howdie Python folks! I am very new to Python ( 3rd day now ) and it has already earned its place as my fav. language to work in. I hope to continue, and I really would appreciate some good resources if anybody would care to contribute.
My current head-scratcher concerns something I can do in Perl which I would like to have duplicated for Python. I have noticed that it is not possible to increment an unset value in Python, so I would like to know how to duplicate the following bit of code using Python dictionaries.
[expletives deleted]
freq_dict = {}
....
if thing in freq_dict:
freq_dict[thing] += 1
else:
freq_dict[thing] = 1
or, less plainly,
freq_dict[thing] = freq_dict.get(thing, 0) + 1
John Machin wrote: freq_dict = {} ... if thing in freq_dict: freq_dict[thing] += 1 else: freq_dict[thing] = 1
or, less plainly,
freq_dict[thing] = freq_dict.get(thing, 0) + 1
or
try:
freq_dict[thing] += 1
except KeyError:
freq_dict[thing] = 1
STeVe
In article <0K********************@comcast.com>, Steven Bethard
<st************@gmail.com> wrote: I don't speak Perl, but based on your output, I'd probably do something like:
py> lines = ["1,2,3,4,5", "2,3,4,5", "3,4,5", "4,5", "5"] py> counts = {} py> for items in lines: ... for item in items.split(','): ... counts[item] = counts.get(item, 0) + 1 ... py> for key in sorted(counts, key=counts.__getitem__, reverse=True): ... print 'Key: %s Frequency: %s' % (key, '*'*counts[key]) ... Key: 5 Frequency: ***** Key: 4 Frequency: **** Key: 3 Frequency: *** Key: 2 Frequency: ** Key: 1 Frequency: *
I'm probably missing a few subtleties, but hopefully this will get you started.
STeVe
Thanks Steven. This helped a lot. Exactly what I was looking for
--
Koncept <<
"The snake that cannot shed its skin perishes. So do the spirits who are
prevented from changing their opinions; they cease to be a spirit." -Nietzsche This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
by: Fred Ma |
last post by:
Hello,
This is not a troll posting, and I've refrained from
asking because I've seen similar threads get all
nitter-nattery. But I really want to make a decision
on how best to invest my time....
|
by: John F Dutcher |
last post by:
Can anyone comment on why the code shown in the Python error is in
some way incorrect...or is there a problem with Python on my hoster's
site ??
The highlites don't seem to show here...but line...
|
by: Xah Lee |
last post by:
# -*- coding: utf-8 -*-
# Python
# to open a file and write to file
# do
f=open('xfile.txt','w')
# this creates a file "object" and name it f.
# the second argument of open can be
|
by: surfunbear |
last post by:
I've read some posts on Perl versus Python and studied a bit of my
Python book.
I'm a software engineer, familiar with C++ objected oriented
development, but have been using Perl because it is...
|
by: ajikoe |
last post by:
Hi,
I tried to follow the example in swig homepage.
I found error which I don't understand.
I use bcc32, I already include directory where my python.h exist in
bcc32.cfg.
/* File : example.c...
|
by: rurpy |
last post by:
Is there an effcient way (more so than cgi) of using Python
with Microsoft IIS? Something equivalent to Perl-ISAPI?
|
by: Edward Elliott |
last post by:
This is just anecdotal, but I still find it interesting. Take it for what
it's worth. I'm interested in hearing others' perspectives, just please
don't turn this into a pissing contest.
I'm in...
|
by: Andrew Robert |
last post by:
I have two Perl expressions
If windows:
perl -ple "s/()/sprintf(q#%%%2X#, ord $1)/ge" somefile.txt
If posix
perl -ple 's/()/sprintf("%%%2X", ord $1)/ge' somefile.txt
|
by: vj |
last post by:
I have a perl script which connect to network stream using sockets.
The scripts first logins in to the server and then parses the data
comming from the socket.
Statement 1:
my $today =...
|
by: ryjfgjl |
last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
|
by: ryjfgjl |
last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
|
by: emmanuelkatto |
last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud.
Please let me know.
Thanks!
Emmanuel
|
by: BarryA |
last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
|
by: Sonnysonu |
last post by:
This is the data of csv file
1 2 3
1 2 3
1 2 3
1 2 3
2 3
2 3
3
the lengths should be different i have to store the data by column-wise with in the specific length.
suppose the i have to...
|
by: Hystou |
last post by:
There are some requirements for setting up RAID:
1. The motherboard and BIOS support RAID configuration.
2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
|
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...
|
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,...
|
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...
| |