Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #54522 > unrolled thread
| Started by | Vlastimil Brom <vlastimil.brom@gmail.com> |
|---|---|
| First post | 2013-09-21 01:25 +0200 |
| Last post | 2013-09-21 01:25 +0200 |
| Articles | 1 — 1 participant |
Back to article view | Back to comp.lang.python
This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by
below is the oldest one visible, not the original post.
Re: Iterate through a list of tuples for processing Vlastimil Brom <vlastimil.brom@gmail.com> - 2013-09-21 01:25 +0200
| From | Vlastimil Brom <vlastimil.brom@gmail.com> |
|---|---|
| Date | 2013-09-21 01:25 +0200 |
| Subject | Re: Iterate through a list of tuples for processing |
| Message-ID | <mailman.209.1379719522.18130.python-list@python.org> |
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 top | Article view | comp.lang.python
csiph-web