Hello everyone,
I want to convert a tuple to a list, and I expected this behavior:
list(('abc','de f')) -> ['abc','def']
list(('abc')) -> ['abc']
But Python gave me this behavior:
list(('abc','de f')) -> ['abc','def']
list(('abc')) -> ['a','b','c']
How do I do get Python to work like the in former case?
Many thanks!
David 11 2938
('abc') is not a tuple - this is an unfortunate result of using ()'s as
expression grouping *and* as tuple delimiters. To make ('abc') a
tuple, you must add an extra comma, as ('abc',). list( ('abc',) )
['abc']
-- Paul
Hi,
Thanks for your reply! A new thing learned....
Allow me to follow that up with another question:
Let's say I have a result from a module called pyparsing:
Results1 = ['abc', 'def']
Results2 = ['abc']
They are of the ParseResults type: type(Results1)
<class 'pyparsing.Pars eResults'> type(Results2)
<class 'pyparsing.Pars eResults'>
I want to convert them into Python lists. list() will work fine on
Results1, but on Results2, it will return:
['a', 'b', 'c']
Because 'abc' is a string. But I want it to return ['abc'].
In short, my question is: how do I typecast an arbitrary object,
whether a list-like object or a string, into a Python list without
having Python split my strings into characters?
Thanks very much for your help!
David
p.s. I know pyparsing has an asList() method, but let's just say I am
unable to use it in my circumstances. vd********@gmai l.com wrote: Hi,
Thanks for your reply! A new thing learned....
Allow me to follow that up with another question:
Let's say I have a result from a module called pyparsing:
Results1 = ['abc', 'def'] Results2 = ['abc']
They are of the ParseResults type:
type(Results1) <class 'pyparsing.Pars eResults'> type(Results2)
<class 'pyparsing.Pars eResults'>
I want to convert them into Python lists. list() will work fine on Results1, but on Results2, it will return:
['a', 'b', 'c']
Because 'abc' is a string. But I want it to return ['abc'].
In short, my question is: how do I typecast an arbitrary object, whether a list-like object or a string, into a Python list without having Python split my strings into characters?
This seems like a glitch in pyparsing. If a ParseResults class emulates
a list, it should do so every time, not only if there is more than one
value in it.
Reinhold
"Reinhold Birkenfeld" <re************ ************@wo lke7.net> wrote in
message news:3i******** ****@individual .net... vd********@gmai l.com wrote: Hi,
Thanks for your reply! A new thing learned....
Allow me to follow that up with another question:
Let's say I have a result from a module called pyparsing:
Results1 = ['abc', 'def'] Results2 = ['abc']
They are of the ParseResults type:
> type(Results1) <class 'pyparsing.Pars eResults'>> type(Results2) <class 'pyparsing.Pars eResults'>
I want to convert them into Python lists. list() will work fine on Results1, but on Results2, it will return:
['a', 'b', 'c']
Because 'abc' is a string. But I want it to return ['abc'].
In short, my question is: how do I typecast an arbitrary object, whether a list-like object or a string, into a Python list without having Python split my strings into characters?
This seems like a glitch in pyparsing. If a ParseResults class emulates a list, it should do so every time, not only if there is more than one value in it.
Unfortunately, I've seen that behavior a number of times:
no output is None, one output is the object, more than one
is a list of objects. That forces you to have checks for None
and list types all over the place. Granted, sometimes your
program logic would need checks anyway, but frequently
just returning a possibly empty list would save the caller
a lot of grief.
John Roth Reinhold
David -
I'm not getting the same results. Run this test program:
---------------
import pyparsing as pp
import sys
def test(s):
results = pp.OneOrMore( pp.Word(pp.alph as) ).parseString( s )
print repr(s),"->",list(results )
print "Python version:", sys.version
print "pyparsing version:", pp.__version__
test("abc def")
test("abc")
---------------
The output I get is:
Python version: 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit
(Intel)]
pyparsing version: 1.3.1
'abc def' -> ['abc', 'def']
'abc' -> ['abc']
What versions of pyparsing and Python are you using?
-- Paul
John -
I just modified my test program BNF to use ZeroOrMore instead of
OneOrMore, and parsed an empty string. Calling list() on the returned
results gives an empty list. What version of pyparsing are you seeing
this None/object/list behavior?
-- Paul
On Mon, Jun 27, 2005 at 08:21:41AM -0600, John Roth wrote: Unfortunately, I've seen that behavior a number of times: no output is None, one output is the object, more than one is a list of objects. That forces you to have checks for None and list types all over the place.
maybe you can at least push this into a single convenience function...
def destupid(x, constructor=tup le, sequencetypes=( tuple, list)):
if x is None: return constructor()
if isinstance(x, sequencetypes): return x
return constructor((x, ))
Jeff
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.1 (GNU/Linux)
iD8DBQFCwCU1Jd0 1MZaTXX0RAivoAK CKcSf5YQaOSp3HW DYnctqzYzxKHwCe PRb2
j564UN61oP7i8Cy oy1VHxL0=
=rasL
-----END PGP SIGNATURE-----
Modified version of test program, to handle empty strings -> empty
lists.
import pyparsing as pp
import sys
def test(s):
results = pp.ZeroOrMore( pp.Word(pp.alph as) ).parseString( s )
print repr(s),"->",list(results )
print "Python version:", sys.version
print "pyparsing version:", pp.__version__
test("abc def")
test("abc")
test("")
Prints:
Python version: 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit
(Intel)]
pyparsing version: 1.3.1
'abc def' -> ['abc', 'def']
'abc' -> ['abc']
'' -> []
Hi Paul and everyone else,
I ran the script and here's what I got:
Python version: 2.4.1 (#2, Mar 31 2005, 00:05:10)
[GCC 3.3 20030304 (Apple Computer, Inc. build 1666)]
pyparsing version: 1.3
'abc def' -> ['abc', 'def']
'abc' -> ['abc']
It seems to work fine.
I figured out what my problem was: my earlier description was
erroneous. The type for Results2 was actually 'str', not
'pyparsing.Pars eResults' as I had mentioned. (I was typing from memory
-- I didn't actually run my code.... sorry, my bad).
It seems that the way I was parsing it, I sometimes got
pyparsing.parse Results lists, and sometimes got *strings* (not
actually single-element lists as I thought).
I had expected pyparsing results to always return lists, I guess with
my token description below, it doesn't. Here's the bit of code I've
wrote:
from pyparsing import *
unit = Word(alphanums)
section = unit + Literal(':').su ppress()
line = ~section + Combine(unit + SkipTo(Literal( ';'), include=True))
block = ZeroOrMore(line )
file = Dict(ZeroOrMore (Group(section + block)))
Results = dict(file.parse String(MyFileSt ring)
Where MyFileStrings (the string I want to parse) is something like
this:
var:
x, y, z;
constraints:
x <= 1;
y <= 2;
z <= 3;
And the results I'd get would be something like this: Results
{'var': 'x, y, z;', 'constraints': (['x <= 1', 'y <= 2', 'z <= 3'],
{})}
So going along Jeff Epler's line of thinking, I wrote a convenience
function:
def convertToList(i nput):
if type(input) == str:
output = [input]
else:
output = input
return output
So when I iterate through the keys of the Results dictionary, I just
have to convertToList(v alue) and I will always get a list.
Thanks for your feedback, everyone!
(and embarassingly, I just realized I was talking to the author of
pyparsing. Thanks for pyparsing, Paul! I'm using it to write a
mini-language for defining process control models used in chemical
engineering, and it has really given me a lot of leverage in terms of
churning actual working code out in minimal time. I was thinking of
doing it the lex/yacc way at first, but pyparsing is so much easier.) This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: lester |
last post by:
a pre-beginner's question:
what is the pros and cons of .net, compared to ++
I am wondering what can I get if I continue to learn C# after I have learned
C --> C++ --> C# ??
I think there must be many know the answer here.
thanks
|
by: Shamrokk |
last post by:
My application has a loop that needs to run every 2 seconds or so. To
acomplish this I used...
"Thread.Sleep(2000);"
When I run the program it runs fine. Once I press the button that starts the
looping function the window becomes unmovable and cannot close under its own
direction (the upper right "close 'X'")
My first attempt to solve the problem was to have the looping function
execute as its own thread, the idea being this would...
|
by: Blaze |
last post by:
I am doing the first walk through on the Visual Studio .Net walkthrough book
to learn a little about programming. I am having issues with the first
tutorial not running correctly. It seems that the build fails with what the
book tells me to do.
Specifically, I am doing this:
public authors1 GetAuthors()
{
authors1 authors = new Authors1();
|
by: Tor Aadnevik |
last post by:
Hi,
I have a problem converting values from Single to double.
eg. When the Single value 12.19 is converted to double, the result is
12.1899995803833.
Anyone know how to avoid this?
Regards Totto
|
by: xfile |
last post by:
Hello,
I am very new to donet and wondering how to solve the following scenario:
(1) Our current hosted site has .Net 1.1 and can be upgraded to 2.0 if
needed. Some downtime are expected and may have unexpected problems though.
(2) Local environment installed both 1.1 and 2.0 framework and 2.0 SDK.
(3) Currently, all our ASP and HTML pages are working fine but we are
| |
by: hharry |
last post by:
hello all,
switching to c# from vb.net and had quick syntax question...
in vb:
Dim httpRequest as HttpWebRequest
httpRequest = WebRequest.Create( _
"http://www.winisp.net/goodrich/default.htm")
|
by: RaulAbHK |
last post by:
Dear all,
I guess this is a basic question with an easy answer but I am a
beginner and I would much apreciate your feedbacks.
Let's say I have a library with some functionality to perform some
image processing on jpeg images.
One of functions in the library is similar to this:
myfunction_effect (&out_instance, &mysettings, I8 *buf_in, I32
|
by: Rangy |
last post by:
Hi,
I've decided to take the plunge and move from tables to a pure css
layout. I still "think" in tables when I do my layouts and I was
wondering the following:
I have a simple, standard two column layout:
header
nav content
|
by: subramanian100in |
last post by:
In the book, C++ Coding Standards book by Hereb Sutter and Andrei
Alexandrescu, in Item 40 on pages 86-87 viz, "Avoid providing implicit
conversions", the authors have advised the use of named functions that
offer conversions instead of conversion operators.
In page 87, example 2: Errors that work.
class String
{
// ...
|
by: darren |
last post by:
Hi there
Im working on an assignment that has me store data in a buffer to be
sent over the network. I'm ignorant about how C++ stores data in an
array, and types in general.
If i declare an array of chars that is say 10 bytes long:
char buff;
does this mean that i can safely store 80 bits of data?
|
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,...
| |
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...
|
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,...
|
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...
|
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 launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
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...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
| |
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
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...
| |