迭代' int'将for循环转换为while循环时的值

时间:2017-09-11 05:34:46

标签: python

我已经设置了创建程序的任务,该程序使用while循环从两个关键字之间的文本文件中提取数据,创建一个元组列表(日期为列表,数据值为整数)< / p>

E.g。

<begin step data>
2001-01-01,12776
2001-01-02,15128
<end step data>

将其提取为[('2001-01-01', 12776), ('2001-01-02', 15128)]

等格式

我开始使用for循环解决它以使其更容易,我最终得到了这段代码,它给了我正确的答案:

def read_records_from_file(filename):

    """ bla """

    mylist = []
    line = open(filename).read()
    start = '<begin step data>'
    end = '<end step data>'
    startpos = line.find(start) + len(start)
    endpos = line.find(end, startpos)
    data = line[startpos:endpos]
    mylist.append(data.split())

    desired = []
    for element in mylist[0]:
        element = element.split(',')

        desired.append((element[0],int(element[1])))  

    return desired

这是我将其转换为while循环的方法:

def read_records_from_file(filename):

    """ bla """

    mylist = []
    line = open(filename).read()
    start = '<begin step data>'
    end = '<end step data>'
    startpos = line.find(start) + len(start)
    endpos = line.find(end, startpos)
    data = line[startpos:endpos]
    mylist.append(data.split())

    desired = []

    element = 0

    while element < len(mylist[0]):
        element = element.split(',')
        desired.append((element[0],int(element[1]))) 
        element += 1

    return desired

但这给了我一个错误'int' object has no attribute 'split'。我很困惑,我将它更改为while循环使其将其作为int而不是list进行读取。

2 个答案:

答案 0 :(得分:2)

For语句可以在while中转换为:

element = 0
while element < len(mylist[0]):
    data = mylist[0][element].split(',')
    desired.append((data[0],int(data[1]))) 
    element += 1

你可以试试Pythonic方式:

>>> data = "2001-01-01,12776 2001-01-02,15128"
>>> data = data.split()
>>> print data
['2001-01-01,12776', '2001-01-02,15128']
>>> final_data = []
>>> for d in data:
    temp = tuple(d.split(","))
    temp_tuple = (temp[0],int(temp[1]))
    final_data.append(temp_tuple)   

>>> print final_data
[('2001-01-01', '12776'), ('2001-01-02', '15128')]

答案 1 :(得分:0)

st = "2001-01-01,12776 2001-01-02,15128"
final_list = []
for elem in st.split():
   date = elem.split(",")[0]
   data = elem.split(",")[-1]
   final_list.append((date, int(data)))
print final_list

您也可以使用此代码生成输出。