简体   繁体   中英

How to convert a list of tuples of floats to list of strings in Python?

I have a list of tuples as follows -

my_list = [(0, nan), (20.307, 0.14045), (-16.879, 0.09363), (4.598, 0.06323)]

This list is a result of -

my_list = list(zip(list_a,list_b))

where list_b was created by appending the variances calculated from a series, hence the nan .

The expected output is -

my_list = ['0, nan','20.307, 0.14045', '-16.879, 0.09363', '4.598, 0.06323']

I tried looping through my_list but I am getting the error - NameError: name 'nan' is not defined

Please guide. Thanks

float("nan") is how python represents NaN .

you could do just this:

my_list = [(0, float("nan")), (20.307, 0.14045), (-16.879, 0.09363), (4.598, 0.06323)]

ret = [', '.join(str(i) for i in items) for items in my_list]
# ['0, nan', '20.307, 0.14045', '-16.879, 0.09363', '4.598, 0.06323']

or if there are always just two items in your list you could use an f-string:

ret = [f'{a}, {b}' for a, b in my_list]
my_list = [(0, None), (20.307, 0.14045), (-16.879, 0.09363), (4.598, 0.06323)]

result = [f'{x[0]},{x[1]}' for x in my_list]

you can do it with this for each tuple in list add a string that consist first item and second item

Your question is somewhat unclear, but let me answer to the best of my abilities. In any case, first thing you may need to do is:

from math import nan

to allow usage of nan literal. If you want to convert my_list to strings, there is a oneliner that can do it:

my_list_strings = [", ".join(map(str, one_tuple)) for one_tuple in my_list]

Or, did you want my_list to be list of strings in the first place? One way to achieve that:

my_list = []
for single_str in zip(list_a, list_b):
    my_list.append(str(single_str[0]) + ", " + str(single_str[1]))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM