【问题标题】:in my for loop .split() only works once在我的 for 循环中 .split() 只工作一次
【发布时间】:2017-09-12 14:33:03
【问题描述】:

所以我有这个应用程序。它记录来自加速度计的数据。这是数据的格式。它保存在 .csv 文件中。

time, x, y, z
0.000000,0.064553,-0.046095,0.353776

这是在我的程序顶部声明的变量。

length = sum(1 for line in open('couchDrop.csv'))
wholeList = [length]
timeList = [length]#holds a list of all the times
xList = [length]
yList = [length]
zList = [length]

我正在尝试创建四个列表;时间,x,y,z。当前,整个数据文件存储在一个列表中。列表中的每一行包含 4 个数字,分别代表时间、x、y 和 z。我需要将 wholeList 拆分为四个不同的列表。这是发生这种情况的子例程:

def easySplit():
    print "easySplit is go "
    for i in range (0, length):
        current = wholeList[i]
        current = current[:-2]  #gets rid of a symbol that may be messing tings up
        print current
        print i
        timeList[i], xList[i], yList[i], zList[i] = current.split(',')
        print timeList[i]
        print xList[i]
        print yList[i]
        print zList[i]
        print ""

这是我得到的错误:

Traceback (most recent call last):
  File "/home/william/Desktop/acceleration plotter/main.py", line 105, in          <module>
    main()
   File "/home/william/Desktop/acceleration plotter/main.py", line 28, in main
easySplit()
  File "/home/william/Desktop/acceleration plotter/main.py", line 86, in easySplit
timeList[i], xList[i], yList[i], zList[i] = current.split(',')
IndexError: list assignment index out of range`

另一个奇怪的事情是我的点分割似乎在第一次通过循环时工作正常。

任何帮助将不胜感激。

【问题讨论】:

    标签: python list loops csv split


    【解决方案1】:

    对于这样的数据操作,我建议使用 Pandas。在一行中,您可以将 CSV 中的数据读入 Dataframe。

    import pandas as pd
    df = pd.read_csv("couchDrop.csv")
    

    然后,您可以轻松地按名称选择每一列。您可以将数据作为pd.Series 进行操作,或者作为np.array 进行操作,或者转换为列表。例如:

    x_list = list(df.x)
    

    您可以在http://pandas.pydata.org/pandas-docs/stable/10min.html找到更多关于熊猫的信息。

    编辑:原始代码的错误是xList = [length] 之类的语法不会创建长度为length 的列表。它创建一个长度为 1 的列表,其中包含一个值为 length 的 int 元素。

    【讨论】:

      【解决方案2】:

      代码行 wholeList = [length] 不会创建长度 = length 的列表。它创建了一个列表,其中只有一个元素是整数length,所以如果你要print(wholeList),你只会看到[3] 由于列表在 python 中是可变的,您可以只使用 wholeList =[] 并继续向其附加元素。它不必是特定的长度。

      当您执行从 WholeList 派生的 current.split(',') 时,它会尝试仅拆分可用于第一次迭代的数据,即 [3]

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-12-08
        • 1970-01-01
        • 2016-01-09
        • 1970-01-01
        • 2023-03-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多