【问题标题】:Splitting a string of values into multiple strings将一串值拆分为多个字符串
【发布时间】:2021-01-30 10:12:06
【问题描述】:

我目前正在开发一个程序,该程序从 csv 文件中获取一组列表,并将它们组合在一起。我想出的程序是:

List_one = []                  
with open("trees.csv") as f:    
    skiplines = f.readline()    
    for line in f:
          res = line.split(" ")    
          List_one.append(res)      
    for i in List_one:
        (i[0]) = (i[0]).rstrip("\n")    
print (List_one)

我现在得到的是一组列表,但问题是这些列表是字符串,我希望它们作为浮点数。列表如下所示:

[['1,8.3,70,10.3'], ['2,8.6,65,10.3'], ['3,8.8,63,10.2'], ['4,10.5,72,16.4'], ['5,10.7,81,18.8'], ['6,10.8,83,19.7'], ['7,11.0,66,15.6'], ['8,11.0,75,18.2'], ['9,11.1,80,22.6'], ['10,11.2,75,19.9'], ['11,11.3,79,24.2'], ['12,11.4,76,21.0'], ['13,11.4,76,21.4'], ['14,11.7,69,21.3'], ['15,12.0,75,19.1'], ['16,12.9,74,22.2'], ['17,12.9,85,33.8'], ['18,13.3,86,27.4'], ['19,13.7,71,25.7'], ['20,13.8,64,24.9'], ['21,14.0,78,34.5'], ['22,14.2,80,31.7'], ['23,14.5,74,36.3'], ['24,16.0,72,38.3'], ['25,16.3,77,42.6'], ['26,17.3,81,55.4'], ['27,17.5,82,55.7'], ['28,17.9,80,58.3'], ['29,18.0,80,51.5'], ['30,18.0,80,51.0'], ['31,20.6,87,77.0']]

正如你们所看到的,我也不能在列表一上使用 float(),因为列表本身就是一个完整的字符串。有没有办法通过索引来拆分列表,所以我得到:

['1', '8.3', '70', '10.3'].....

欢迎任何帮助。

【问题讨论】:

  • res = line.split(",")

标签: python string list indexing split


【解决方案1】:

这可能会有所帮助:

l =[['1,8.3,70,10.3'], ['2,8.6,65,10.3'], ['3,8.8,63,10.2'], ['4,10.5,72,16.4']]

l2 =[]
for x in l:
    a =x[0].split(",")
    l2.append(a)
print(l2)

享受吧!

【讨论】:

    【解决方案2】:

    你可以说:

    res = line.split(" ")
    
    # map takes a function as the first arg and a list as the second
    list_of_floats = list(map(lambda n: float(n), res.split(",")))
    
    # then you can
    List_one.append(list_of_floats)
    

    这仍然会给您一个嵌套列表,因为您在 for line in f: 的每次迭代期间都会推送一个列表,但每个列表至少是您指定的浮点数。

    如果您只想获得一个浮动列表而不是初始 line.split(' '),您可以使用正则表达式分割从 csv 读取的行:

    import re # at the top of your file
    
    res = re.split(r'[\s\,]', line)
    list_of_floats = list(map(lambda n: float(n), res))
    List_one.append(list_of_floats)
    

    【讨论】:

      【解决方案3】:

      如果需要,您可以用逗号分隔字符串。不过,您可能应该在将它们附加到 List_one 之前完成所有操作。

      res = [float(x) for x in line.split(" ")[0].split(",")]
      List_one.append(res)
      

      这是否如您所愿?抱歉,我不确定输入的格式,所以我有点猜测

      【讨论】:

        【解决方案4】:

        "line.split(',')" 用 "," 分割字符串并返回列表。 对于字符串 '1,8.3,70,10.3',它将返回 [1, 8.3, 70, 10.3]

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-06-14
          • 2013-05-28
          • 2016-02-21
          • 1970-01-01
          • 2022-11-23
          • 2010-09-19
          相关资源
          最近更新 更多