473,698 Members | 2,932 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

write a loopin one line; process file paths

is there a way to condense the following loop into one line?

# -*- coding: utf-8 -*-
# python

import re, os.path

imgPaths=[u'/Users/t/web/Periodic_dosage _dir/lanci/t4/oh/DSCN2059m-s.jpg',
u'/Users/t/web/Periodic_dosage _dir/lanci/t4/oh/DSCN2062m-s.jpg',
u'/Users/t/web/Periodic_dosage _dir/lanci/t4/oh/DSCN2097m-s.jpg',
u'/Users/t/web/Periodic_dosage _dir/lanci/t4/oh/DSCN2099m-s.jpg',
u'/Users/t/web/Icons_dir/icon_sum.gif']

# change the image path to the full sized image, if it exists
# that is, if image ends in -s.jpg, find one without the '-s'.
temp=imgPaths[:]
imgPaths=[]
for myPath in temp:
p=myPath
(dirName, fileName) = os.path.split(m yPath)
(fileBaseName, fileExtension)= os.path.splitex t(fileName)
if(re.search(r'-s$',fileBaseNam e,re.U)):
p2=os.path.join (dirName,fileBa seName[0:-2]) + fileExtension
if os.path.exists( p2): p=p2
imgPaths.append (p)

temp=[]
print imgPaths

Xah
xa*@xahlee.org
http://xahlee.org/

Oct 18 '05 #1
14 2058

Xah Lee wrote:
is there a way to condense the following loop into one line?

# -*- coding: utf-8 -*-
# python

import re, os.path

imgPaths=[u'/Users/t/web/Periodic_dosage _dir/lanci/t4/oh/DSCN2059m-s.jpg',
u'/Users/t/web/Periodic_dosage _dir/lanci/t4/oh/DSCN2062m-s.jpg',
u'/Users/t/web/Periodic_dosage _dir/lanci/t4/oh/DSCN2097m-s.jpg',
u'/Users/t/web/Periodic_dosage _dir/lanci/t4/oh/DSCN2099m-s.jpg',
u'/Users/t/web/Icons_dir/icon_sum.gif']

# change the image path to the full sized image, if it exists
# that is, if image ends in -s.jpg, find one without the '-s'.
temp=imgPaths[:]
imgPaths=[]
for myPath in temp:
p=myPath
(dirName, fileName) = os.path.split(m yPath)
(fileBaseName, fileExtension)= os.path.splitex t(fileName)
if(re.search(r'-s$',fileBaseNam e,re.U)):
p2=os.path.join (dirName,fileBa seName[0:-2]) + fileExtension
if os.path.exists( p2): p=p2
imgPaths.append (p)

temp=[]
print imgPaths


this is of interest to me, because i wanted to illustrate functional
programing, and Python's short-coming of it. (if you go to wikipedia
and read the article on Python, it will proudly say that Python
supports functional programing. A huge fucking lie. (more fantastic
fucking lies in the Perl article. And it is impossible to correct them,
because there is an army of ignorant morons, usually militant too, not
shy to do justice for humanity with heartiness.) )

In functional programing proper, the following loop for example would
be a single line. Why? because in fp, one is focused on the input &
output and less on the details how it is done. So here, one simply
reads the comment there and that'd be it. The one-line code would be in
the form of impPaths = f(impPaths), where f is a function made on the
spot.

So, in fp the source code tends to take the form of paragraphs of
algorithmic units, as opposed one million lines of code filling the
page.

I would have, written the following in a one-line. But in Python this
is impossible. (if possible, probably something so unusual and
unreadable)

.... Here we may want to make a note on what does it mean to say that a
programing language supports functional programing. The FP style,
basically means that one writes pure functions and apply them to
expressions. That is, subroutines whose behavior are purely that of
input and output. (i.e. so-called without side-effects) But if one
programs in FP style, certain patterns of coding emerges. For example,
a lambda construct, sequencing of functions, assigning and moving of
functions, application of functions etc, and such languages naturally
developed many features in that direction such as types, macros, many
specialized loop constructs (recursion, nesting) and many other
features that goes by abstruse names...etc.

so here, if we judge Python (or Perl), why should we say it supports
functional programing? Simply because it is possible to define
subroutines without side-effects? What else, really, functional
language features does Python support? Can we really say, that a
functional programing coming to Python will find it reasonably supports
his FP coding style?

I would like to see the “also support functional programing”
removed in the wikipedia Python article.
( http://en.wikipedia.org/wiki/Python_...mming_language )

(Perl the language, can arguably be said to support some functional
programing. (those Schwatchzian etc Transform for example, is a epitome
of functional programing.) However, Perl does not support
Object-Oriented programing.)

The Perl article is filled with more egregious lies. (In the past year)
I've tried to mend the article about every 3 months or so, tentatively
on obvious and technical and non-controversial items that's purely
propaganda but got denied by the Perl fuckfaces. I have written a full
page of criticism but the human animal fuckers handily censored it too.
If you think i have a point, please add this link to the Perl page's
external links.
http://xahlee.org/UnixResource_dir/perlr.html (book review and
criticism on Perl & community)

Xah
xa*@xahlee.org
http://xahlee.org/

Oct 18 '05 #2
Xah Lee wrote:
If you think i have a point, ...


You have neither that, nor a clue.

(Newsgroups line trimmed to reduce the effects of cross-posting trolls.)

-Peter
Oct 19 '05 #3

Peter Hansen wrote:
Xah Lee wrote:
If you think i have a point, ...


You have neither that, nor a clue.


Dear Peter Hansen,

My messages speak themselfs. You and your cohorts's stamping of it does
not change its nature. And if this is done with repetitiousness , it
gives away your nature.

It is not necessary to shout against me. But if you must refute (and
that is reasonable), try to put content into your posts.
(see Philosophies of Netiquette at
http://xahlee.org/UnixResource_dir/w...etiquette.html)

If you deem fit, create a alt.fan.XahLee, and spare the rest of Python
community of your politics. I appreciate your fandom.

Xah
xa*@xahlee.org
http://xahlee.org/

Oct 19 '05 #4
what do you mean by one line ? Using map/filter, I believe it is
possible.

Somthing like:

map(lambda (s,f): os.path.exists( f) and f or s,
map(lambda x: (x, re.replace(x, "-s","")), imgPaths)

My regex is a bit rusty but I hope you got the idea of what I am trying
to do. If there is a way to make the re return without destroying x,
the outer map is not needed I believe(that is run it twice, once for
getting the filename to do the testing, then again based on the testing
result).

Xah Lee wrote:
is there a way to condense the following loop into one line?

# -*- coding: utf-8 -*-
# python

import re, os.path

imgPaths=[u'/Users/t/web/Periodic_dosage _dir/lanci/t4/oh/DSCN2059m-s.jpg',
u'/Users/t/web/Periodic_dosage _dir/lanci/t4/oh/DSCN2062m-s.jpg',
u'/Users/t/web/Periodic_dosage _dir/lanci/t4/oh/DSCN2097m-s.jpg',
u'/Users/t/web/Periodic_dosage _dir/lanci/t4/oh/DSCN2099m-s.jpg',
u'/Users/t/web/Icons_dir/icon_sum.gif']

# change the image path to the full sized image, if it exists
# that is, if image ends in -s.jpg, find one without the '-s'.
temp=imgPaths[:]
imgPaths=[]
for myPath in temp:
p=myPath
(dirName, fileName) = os.path.split(m yPath)
(fileBaseName, fileExtension)= os.path.splitex t(fileName)
if(re.search(r'-s$',fileBaseNam e,re.U)):
p2=os.path.join (dirName,fileBa seName[0:-2]) + fileExtension
if os.path.exists( p2): p=p2
imgPaths.append (p)

temp=[]
print imgPaths

Xah
xa*@xahlee.org
http://xahlee.org/


Oct 19 '05 #5
Xah Lee wrote:
Xah Lee wrote:
<stupid question> this is of interest to me,


That's why you are replying to yourself
I have written a full
page of criticism but the human animal fuckers handily censored it too.


Who would have predicted that? Maybe you should boycott them.

To those who came to this message looking for pornography, I am sorry
for the misleading keywords. Try adding "pictures" to your search
terms.
There is nothing to see here; just another keyboard wanker.

Python, Perl, Lisp, and Scheme all have one thing in common ---
the people who use them do not need any more of this drivel.

-- Programmer in Chief

Oct 19 '05 #6
Thanks. Here's how the inner loop should be:

imgPaths2=map(l ambda x: (x, re.sub( r"^(.+?)-s(\.[^.]+)$",r"\1\2", x)),
imgPaths)

though, now i just need something like

map( lambda x: os.path.exists( s)? x[1]:x[0],impPaths2)

but Pyhton doesn't support the
test ? trueResult : falseResult
construct.

(the semantic of this construct, of a conditional that RETURNS A
EXPRESSION, all in one line, is important in functional programing.
Perl supports it. In Mathematica, it's simply the form If[testExpr,
trueExpr, falseExpr]. In lisp, similar: (if testExpr trueExpr
falseExpr) )

is there a way to similate it?

Xah
xa*@xahlee.org
http://xahlee.org/

bo****@gmail.co m wrote:
what do you mean by one line ? Using map/filter, I believe it is
possible.

Somthing like:

map(lambda (s,f): os.path.exists( f) and f or s,
map(lambda x: (x, re.replace(x, "-s","")), imgPaths)

My regex is a bit rusty but I hope you got the idea of what I am trying
to do. If there is a way to make the re return without destroying x,
the outer map is not needed I believe(that is run it twice, once for
getting the filename to do the testing, then again based on the testing
result).


Oct 19 '05 #7
it will be added in 2.5 I beleve. At the moment, you can:

predicate and <true expression> or <false expression>

like :
os.paths.exists (something) and "print it is there" or "file not found"

I am practicing FP in python and it is in general doable with the help
of itertools and add the needed functions as needed, like scanl/scanl1
etc.

A few things I don't like about python for FP is that it relies heavily
on exception which make these one liners not possible in many case.

Example:

a=[]
a[0] would raise exception

I usually prefer None as a special value which can be handled in normal
flow(filter out, may be "x is None and something or otherthing"). But
the liberal use of Exception force you to structure the program either
in a very odd way(test with hasattr/haskey etc. before use) or needs
lots of try/except blocks. I am using a python XHTML template Kid which
relies on one-liner and found it very difficult.

However, if you don't really need one-liner but just FP style to
shorten the program, it is fine but I just find the try/except block
quite ugly.

Then there is the side effect of iterators/generators which unless you
know can burn you badly(especiall y when you are chaining these objects
in these multiple map/filter calls), as mentioned in another post.

Xah Lee wrote: Thanks. Here's how the inner loop should be:

imgPaths2=map(l ambda x: (x, re.sub( r"^(.+?)-s(\.[^.]+)$",r"\1\2", x)),
imgPaths)

though, now i just need something like

map( lambda x: os.path.exists( s)? x[1]:x[0],impPaths2)

but Pyhton doesn't support the
test ? trueResult : falseResult
construct.

(the semantic of this construct, of a conditional that RETURNS A
EXPRESSION, all in one line, is important in functional programing.
Perl supports it. In Mathematica, it's simply the form If[testExpr,
trueExpr, falseExpr]. In lisp, similar: (if testExpr trueExpr
falseExpr) )

is there a way to similate it?

Xah
xa*@xahlee.org
http://xahlee.org/

bo****@gmail.co m wrote:
what do you mean by one line ? Using map/filter, I believe it is
possible.

Somthing like:

map(lambda (s,f): os.path.exists( f) and f or s,
map(lambda x: (x, re.replace(x, "-s","")), imgPaths)

My regex is a bit rusty but I hope you got the idea of what I am trying
to do. If there is a way to make the re return without destroying x,
the outer map is not needed I believe(that is run it twice, once for
getting the filename to do the testing, then again based on the testing
result).


Oct 19 '05 #8

bo****@gmail.co m wrote:
it will be added in 2.5 I beleve. At the moment, you can:

predicate and <true expression> or <false expression>
Ah, i see. Here's the full code again:

# -*- coding: utf-8 -*-
# python

import re, os.path

imgPaths=[u'/Users/t/t4/oh/DSCN2059m-s.jpg',
u'/Users/t/t4/oh/DSCN2062m-s.jpg', u'/Users/t/t4/oh/DSCN2097m-s.jpg',
u'/Users/t/t4/oh/DSCN2099m-s.jpg', u'/Users/t/Icons_dir/icon_sum.gif']

# change the image path to the full sized image, if it exists
# that is, if image ends in -s.jpg, find one without the '-s'.

imgPaths2=[]
for myPath in imgPaths:
p=myPath
(dirName, fileName) = os.path.split(m yPath)
(fileBaseName, fileExtension)= os.path.splitex t(fileName)
if(re.search(r'-s$',fileBaseNam e,re.U)):
p2=os.path.join (dirName,fileBa seName[0:-2]) + fileExtension
if os.path.exists( p2): p=p2
imgPaths2.appen d(p)

imgPaths3 = map( lambda x: os.path.exists( x[1]) and x[1] or x[0],
map(lambda x: (x, re.sub( r"^(.+?)-s(\.[^.]+)$",r"\1\2", x)),
imgPaths))

print imgPaths2 == imgPaths3

------------------
A few things I don't like about python for FP is that it relies heavily
on exception which make these one liners not possible in many case.
...
yeah i know how it feels. I haven't had much experience with Python
yet... but doing it in Perl gets all twisted. (especially when one
tries to use trees as data structure (nested lists) in Perl)

besides syntactical issues, another thing with doing functional
programing in imperative languages is that they become very inefficent.
Functional languages are optimized by various means of functional
programings styles. Doing them in imperative languages usually comes
with a order of execution penalty because imperative language compilers
are usually dumb.

though, one can't totally blame for Python's lack of ability to do
functional programing. Its language's syntax of using indentations for
blocks by design, pretty much is in odds with functional programing's
sequencing of functions and other ways. (such as generic mechanism for
prefix/postfix syntax, or macros or other transformations and patterns,
or heavy reliance on the free flow of expressions/values)

I don't blame Python that it doesn't cater to functional programing BY
DESIGN. But i do hate the mother fucking fuckheads Pythoners for one
thing that they don't know what functional programing really is, and on
the other hand fucking trumpet their righteousness and lies thru their
teeth of their ignorance. (that Guido guy with his Python 3000 article
on his blog is one example, possibly forgivable in that particular
instance. (http://xahlee.org/perl-python/python_3000.html))

(excuse me for lashing out)

Xah
xa*@xahlee.org
http://xahlee.org/
like :
os.paths.exists (something) and "print it is there" or "file not found"


I am practicing FP in python and it is in general doable with the help
of itertools and add the needed functions as needed, like scanl/scanl1
etc.

A few things I don't like about python for FP is that it relies heavily
on exception which make these one liners not possible in many case.

Example:

a=[]
a[0] would raise exception

I usually prefer None as a special value which can be handled in normal
flow(filter out, may be "x is None and something or otherthing"). But
the liberal use of Exception force you to structure the program either
in a very odd way(test with hasattr/haskey etc. before use) or needs
lots of try/except blocks. I am using a python XHTML template Kid which
relies on one-liner and found it very difficult.

However, if you don't really need one-liner but just FP style to
shorten the program, it is fine but I just find the try/except block
quite ugly.

Then there is the side effect of iterators/generators which unless you
know can burn you badly(especiall y when you are chaining these objects
in these multiple map/filter calls), as mentioned in another post.


Oct 19 '05 #9

Xah Lee wrote:
besides syntactical issues, another thing with doing functional
programing in imperative languages is that they become very inefficent.
Functional languages are optimized by various means of functional
programings styles. Doing them in imperative languages usually comes
with a order of execution penalty because imperative language compilers
are usually dumb.
The itertools module and the new generator feature tries to make this
better as it is lazily evaluated, in a sense. But its side effect is
nasty. Usable though need to twist my mind a bit, not like when I do it
in haskell. But the occasion imperative dip makes some of my programs
easier to code.

though, one can't totally blame for Python's lack of ability to do
functional programing. Its language's syntax of using indentations for
blocks by design, pretty much is in odds with functional programing's
sequencing of functions and other ways. (such as generic mechanism for
prefix/postfix syntax, or macros or other transformations and patterns,
or heavy reliance on the free flow of expressions/values)
That I am not sure. haskell also use this indentation but I don't see a
problem about it. One thing I find it odd though is the @decorator
construct. I just don't understand why it is viewed as simple. It
becomes very ugly IMO when there is a number of it, I am doing some web
apps which requres varies decorators(one over the other).

@format
@login_block
@validate
@something
def my_func():

I find it easier to read and under stand in the form of

format(login_bl ock(validate(so mething(my_func ))))) though haskell's $
and . is even better.

format.login_bl ock.validate.so methin.my_func

I don't blame Python that it doesn't cater to functional programing BY
DESIGN. But i do hate the mother fucking fuckheads Pythoners for one
thing that they don't know what functional programing really is, and on
the other hand fucking trumpet their righteousness and lies thru their
teeth of their ignorance. (that Guido guy with his Python 3000 article
on his blog is one example, possibly forgivable in that particular
instance. (http://xahlee.org/perl-python/python_3000.html))
That seems to be the case, I mean the design. For fairness, list
comphrehension sometimes looks cleaner, though becomes ugly when you do
the pipe/chain like programming in FP(multiple for). This again is an
odd choice. It seems to be a flattening of multiple line for loop, yet
at the same time python seems to be moving towards being more
explicit(no map/filter/etc as they can be done in for loop).

But I believe Python is designed for easy to code and read and maintain
in mind. One has to admit that without some training, FP is not very
intuitive, my head spin when I see haskell code. A for loop is easier
to understand.

Well, if you want clean FP, you can always try haskell which is getting
better and better in terms of real world module support(file system,
network etc).
(excuse me for lashing out)

Xah
xa*@xahlee.org
http://xahlee.org/


Oct 19 '05 #10

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

Similar topics

7
3019
by: Patrick Useldinger | last post by:
Hi, I think I found a bug in the write method of file objects. It seems as if before writing each block, a check was done in order to verifiy that there is enough space left for the *whole* file, not for the *remaining* data to be written. It happens both under 2.3 and 2.2.3. Any ideas?
15
3322
by: Viviana Vc | last post by:
How can I programatically do the equivalent of the following: cacls "C:\Program Files\test" /T /G Everyone:f ? Thanks, Viv
7
4733
by: Steve M | last post by:
I'm trying to invoke a Java command-line program from my Python program on Windows XP. I cannot get the paths in one of the arguments to work right. The instructions for the program describe the following for the command-line arguments: java -jar sforcedataloader.jar -Dsalesforce.config.dir=CONFIG_DIRECTORY They also give an example:
18
4886
by: jas | last post by:
Hi, I would like to start a new process and be able to read/write from/to it. I have tried things like... import subprocess as sp p = sp.Popen("cmd.exe", stdout=sp.PIPE) p.stdin.write("hostname\n") however, it doesn't seem to work. I think the cmd.exe is catching it.
0
3033
by: Peter Horwood | last post by:
I am having trouble writing an XML file out on my localhost development machine. I get: Server Error in '/ProblemSolved' Application. ----------------------------------------------------------- --------------------- Access to the path "c:\inetpub\wwwroot\ProblemSolved\XMLData\Products.xml
3
4539
by: Daniel Billingsley | last post by:
Today I went to compile a solution I've been working on for months. I've been off most of the last few months, so there's been a gap in the work, but I did compile it a few times earlier this week. Today I get a message: Could not write to output file 'D:\DevelopmentProjects\Enterprise\CustomUtilities\obj\Debug\CustomUtilities ..dll' -- 'The process cannot access the file because it is being used by another process. '
88
8042
by: Peter Olcott | last post by:
Cab you write code directly in the Common Intermediate language? I need to optimize a critical real-time function.
2
11325
by: =?Utf-8?B?RGFtZW9u?= | last post by:
Hi - I am attempting to write lines to a file at high volume, multiple threads. Here is my scenario: (initial "WriteToFile" object created via a parent multithreaded process, which receives files, can call custom code for each file received - much like BizTalk) 1. Receive multiple files, each file received creates a "WriteToFile" object
16
4687
by: Hans Fredrik Nordhaug | last post by:
I'm trying to write to a file in the current directory - no remote files. The subject says it all - I can add that both the directory and the file is wordwritable. This happens on a (quite good) free hoster in Norway which doesn't use safe mode, running PHP 5.1.6 as the PHP info below shows ... Test it at: http://home.no.net/moldevbk/fopen-test/?mode=w (write - fails) http://home.no.net/moldevbk/fopen-test/?mode=a (append - ok)...
0
8683
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
8611
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
9170
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
8904
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
8876
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
6531
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
4372
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
4624
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2007
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.