简体   繁体   English

遍历Python中的Float列表

[英]Iterate over Float list in Python

I am trying to iterate over a list of float values using for loop but getting the error. 我试图使用for循环遍历浮点值列表,但收到错误。 I am trying to print the list using enumerate(). 我正在尝试使用enumerate()打印列表。 Is there a better way to iterate over a list of floats? 有没有更好的方法来遍历浮点数列表?

The list has numbers like list_float= [1546626931.138813,1546626931.138954,1546626931.139053,1546626931.139289,.......,1546628078.463885] 列表的编号类似于list_float= [1546626931.138813,1546626931.138954,1546626931.139053,1546626931.139289,.......,1546628078.463885]

Code is: 代码是:

import csv
import datetime
import pandas


filename = open('C:\\Users\\xyz\\Downloads\\BLF File\\output.csv', "w")
log = can.BLFReader('C:\\Users\\xyz\\Downloads\\BLF File\\test.blf')

# print ("We are here!")
log_output = []
timestamp = [] #Variable to store timestamps from blf file
time_del = [] #Variable to store time difference
# filename.write('Timestamp              ID             DLC                 Channel' + '\n')

print('We are here 1')
for time in log:
    time = str(time).split()
    timestamp = float(time[1])
    # print(timestamp)


for count, item in enumerate(timestamp):
    print(count, item)

It is only printing the last float value in the list which is ' 1546628078.463885 ' as below: 它仅打印列表中的最后一个浮点值,即“ 1546628078.463885 ”,如下所示:

0 1
1 5
2 4
3 6
4 6
5 2
6 8
7 0
8 7
9 8
10 .
11 4
12 6
13 3
14 8
15 8
16 5 

In the file I have passed the values are like below: 在我传递的文件中,值如下所示:

['Timestamp:', '1546626926.380693', 'ID:', '0366', 'S', 'DLC:', '8', '25', '80', 'f8', '7f', '00', '00', '00', '00', 'Channel:', '0']
['Timestamp:', '1546626926.381285', 'ID:', '0120', 'S', 'DLC:', '2', '00', '05', 'Channel:', '1']

This loop overwrites timestamp each time, so in the end timestamp is a single float rather than a list of floats. 该循环每次都会覆盖timestamp ,因此最终timestamp是单个浮动而不是浮动列表。

for time in log:
    time = str(time).split()
    timestamp = float(time[1])

You probably want: 您可能想要:

for time in log:
    time = str(time).split()
    timestamp.append(float(time[1]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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