[英]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
.其中
list_b
是通过附加从一系列计算的方差创建的,因此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
我尝试遍历
my_list
但出现错误 - NameError: name 'nan' is not defined
Please guide.请指导。 Thanks
谢谢
float("nan")
is how python represents NaN
.float("nan")
是 python 表示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:或者如果您的列表中总是只有两个项目,您可以使用 f 字符串:
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.允许使用
nan
文字。 If you want to convert my_list
to strings, there is a oneliner that can do it:如果要将
my_list
转换为字符串,有一个 oneliner 可以做到:
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?或者,您是否首先希望
my_list
成为字符串列表? 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]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.