Iterate through a list of tuples for processing
Vlastimil Brom
vlastimil.brom at gmail.com
Fri Sep 20 19:25:13 EDT 2013
2013/9/20 Shyam Parimal Katti <spk265 at 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
More information about the Python-list
mailing list