473,326 Members | 2,013 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,326 software developers and data experts.

Beginner question: Converting Single-Element tuples to list

Hello everyone,

I want to convert a tuple to a list, and I expected this behavior:

list(('abc','def')) -> ['abc','def']
list(('abc')) -> ['abc']

But Python gave me this behavior:

list(('abc','def')) -> ['abc','def']
list(('abc')) -> ['a','b','c']

How do I do get Python to work like the in former case?

Many thanks!

David

Jul 19 '05 #1
11 2910
('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

Jul 19 '05 #2
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.ParseResults'> type(Results2)

<class 'pyparsing.ParseResults'>

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.

Jul 19 '05 #3
vd********@gmail.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.ParseResults'> type(Results2)

<class 'pyparsing.ParseResults'>

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
Jul 19 '05 #4
"Reinhold Birkenfeld" <re************************@wolke7.net> wrote in
message news:3i************@individual.net...
vd********@gmail.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.ParseResults'>
> type(Results2)

<class 'pyparsing.ParseResults'>

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


Jul 19 '05 #5
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.alphas) ).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

Jul 19 '05 #6
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

Jul 19 '05 #7
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=tuple, 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)

iD8DBQFCwCU1Jd01MZaTXX0RAivoAKCKcSf5YQaOSp3HWDYnct qzYzxKHwCePRb2
j564UN61oP7i8Cyoy1VHxL0=
=rasL
-----END PGP SIGNATURE-----

Jul 19 '05 #8
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.alphas) ).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']
'' -> []

Jul 19 '05 #9
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.ParseResults' 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.parseResults 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(':').suppress()
line = ~section + Combine(unit + SkipTo(Literal(';'), include=True))
block = ZeroOrMore(line)
file = Dict(ZeroOrMore(Group(section + block)))
Results = dict(file.parseString(MyFileString)

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(input):
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(value) 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.)

Jul 19 '05 #10
vd********@gmail.com wrote:
if type(input) == str:


You might consider writing this as:

if isinstance(input, basestring):

I don't know if pyparsing ever produces unicode objects, but in case it
does (or it starts to in the future), isinstance is a better call here.

STeVe
Jul 19 '05 #11
Steve -

Good catch - in v1.3, I added some Unicode support for pyparsing,
although I have not gotten much feedback that anyone is using it, or
how well it works. So it is preferable to test against basestring
instead of str.

-- Paul

Jul 19 '05 #12

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

Similar topics

44
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...
8
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...
12
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...
7
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...
6
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...
9
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( _...
6
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...
3
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...
4
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...
3
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...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.