Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #54522

Re: Iterate through a list of tuples for processing

References <CALVX-obUsDkCNHgEAxbpFUxBkyeketYECEz3gF69fPeaMC_Vzw@mail.gmail.com>
Date 2013-09-21 01:25 +0200
Subject Re: Iterate through a list of tuples for processing
From Vlastimil Brom <vlastimil.brom@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.209.1379719522.18130.python-list@python.org> (permalink)

Show all headers | View raw


2013/9/20 Shyam Parimal Katti <spk265@nyu.edu>:
> I have a list of tuples where the number of rows in the list and the number
> of columns in tuples of the list will not be constant. i.e.
>
>  ...> i.e.
>
> list_value = [(‘name1’, 1234, ‘address1’ ), (‘name2’, 5678, ‘address2’),
> (‘name3’, 1011, ‘addre”ss3’)]
>
> I need to access each value to check if the value contains a double quote
> and enclose the string containing double quote with double quotes. The
> transformation should return
>
> list_value = [(‘name1’, 1234, ‘address1’ ), (‘name2’, 5678, ‘address2’),
> (‘name3’, 1011, ‘”addre”ss3”’)]
>
>  ...>
>
>
> Is there a way to make the code concise using list comprehension?
>
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>

Hi,
would the following do, what you want?

>>> orig_list = [('name1', 1234, 'address1' ), ('name2', 5678, 'address2'), ('name3', 1011, 'addre"ss3')]
>>> modif_list = [['"'+elem+'"' if isinstance(elem, basestring) and '"' in elem else elem for elem in row] for row in orig_list]
>>> modif_list
[['name1', 1234, 'address1'], ['name2', 5678, 'address2'], ['name3',
1011, '"addre"ss3"']]
>>>

I guess, you don't mind changing the inner tuples to lists, but the
original structure could be retained as well:
>>> [tuple(['"'+elem+'"' if isinstance(elem, basestring) and '"' in elem else elem for elem in row]) for row in orig_list]
[('name1', 1234, 'address1'), ('name2', 5678, 'address2'), ('name3',
1011, '"addre"ss3"')]
>>>

Of course, you have to decide, whether the readability/conciseness
suits your needs ...

hth,
   vbr

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: Iterate through a list of tuples for processing Vlastimil Brom <vlastimil.brom@gmail.com> - 2013-09-21 01:25 +0200

csiph-web