我有一个如下列表:
['0.0000 0.0012 0.0024 0.0037 0.0049', '0.0061 0.0073 0.0085 0.0097 0.0110', '0.0122 0.0134 0.0146 0.0158 0.0170', '1.0000']
我想从中删除撇号,逗号和空格,并将项目附加到新列表中。输出应如下所示:
[0.0000,0.0012,0.0024,0.0037,0.0049,0.0061,0.0073,0.0085,0.0097,0.0110,0.0122,0.0134,0.0146,0.0158,0.0170,1.0000]
这可能是一项微不足道的任务。有什么建议?
答案 0 :(得分:4)
简单的单行:split
(没有参数,因此它具有将任何数量的空格字符作为分隔符的优点),在列表理解中被2个非嵌套循环展平,同时转换为float
:
a = ['0.0000 0.0012 0.0024 0.0037 0.0049', '0.0061 0.0073 0.0085 0.0097 0.0110', '0.0122 0.0134 0.0146 0.0158 0.0170', '1.0000']
result = [float(x) for e in a for x in e.split()]
print(result)
结果:
[0.0, 0.0012, 0.0024, 0.0037, 0.0049, 0.0061, 0.0073, 0.0085, 0.0097, 0.011, 0.0122, 0.0134, 0.0146, 0.0158, 0.017, 1.0]
答案 1 :(得分:1)
你可以试试这个:
import re
import itertools
s = ['0.0000 0.0012 0.0024 0.0037 0.0049', '0.0061 0.0073 0.0085 0.0097 0.0110', '0.0122 0.0134 0.0146 0.0158 0.0170', '1.0000']
new_s = map(float, itertools.chain(*[re.split('\s+', i) for i in s]))
输出:
[0.0, 0.0012, 0.0024, 0.0037, 0.0049, 0.0061, 0.0073, 0.0085, 0.0097, 0.011, 0.0122, 0.0134, 0.0146, 0.0158, 0.017, 1.0]
答案 2 :(得分:0)
请注意,该列表不包含撇号和逗号。这些是输出的一部分,以显示列表包含字符串。逗号分隔列表中的每个字符串,有一个撇号用于显示字符串的开头,另一个用于显示字符串的结尾。
要管理空白,您可能需要使用split()
。如果在每个字符串上调用此函数,您将获得数字的各个字符串表示形式。如果您想要数字而不是字符串,则需要将它们转换为float
s。这将允许您对数据进行数值运算。
答案 3 :(得分:0)
x = ['0.0000 0.0012 0.0024 0.0037 0.0049', '0.0061 0.0073 0.0085 0.0097 0.0110', '0.0122 0.0134 0.0146 0.0158 0.0170', '1.0000']
list_x = []
for i in x:
list_x.append(i.split(' ')) # Erase 4 whitespaces, add values to a list.
list_final = [a for b in list_x for a in b] # Combine lists.