[Tutor] Zope ZSQL/Python Question
Kent Johnson
kent_johnson at skillsoft.com
Fri Aug 27 22:20:55 CEST 2004
I'm not sure I understand. When the data is ['a', 'b', 'c', 'd'] you want
to output 'a\tb\tc\td' and when the data is ['a', 'd'] you want to output
'a\td'? Piece of cake!
>>> def outputList(actual, possible):
... return '\t'.join([ (x in actual and x or '') for x in possible ])
...
>>> outputList(['a', 'b', 'c', 'd'], 'abcd')
'a\tb\tc\td'
>>> outputList(['a', 'd'], 'abcd')
'a\t\t\td'
Then in your script, instead of i.question04, use outputList(i.question04,
'abcd')
OK, I better explain this or Danny is going to come looking for me :-)
Here is a longer version that does the same thing:
def outputList(actual, possible):
out = []
for x in possible:
if x in actual:
out.append(x)
else:
out.append('')
return '\t'.join(out)
In general, if B can never evaluate to false, then the expression A and B
or C is the same as a ternary operator in C or Java: A ? B : C
(If B can evaluate to false you have to use the more verbose, and much
uglier, (A and [B] or [C])[0] )
The list comprehension takes the place of the loop, and '\t'.join(out) just
concatenates all the elements of out into a string with tab separators
between the elements.
Kent
At 12:47 PM 8/27/2004 -0700, KJZZ Webmaster wrote:
>I am trying to export the results of a zsql method to an excel file
>(actually a tab delimited text file) using python.
>
>Everything is working fairly well, except the columns for questions 4 and 5
>in the table are of the list data type.
>For instance, Question 4 looks like this:
> ['a', 'b', 'c', 'd']
> or
> ['a', 'd']
>depending on which answers a person chose.
>
>In the export, I am looking to have columns and data for Question4a,
>Question4b, Question4c, Question4d
>and simply have empty tabs in place of an answer if there is no data.
>
>My question is really that most colums in the database have a single value,
>however these two columns contain a list.
>How might I handle this?
>
>Thanks for any advice you might have.
>
>John Tynan - webmaster
>KJZZ.org / KBAQ.or
>480.774.8462
>
>
>_______________________________________________
>Tutor maillist - Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor
More information about the Tutor
mailing list