Python嵌套循环迭代列表中的列表

时间:2018-03-03 12:01:47

标签: python python-3.x dictionary

您好我正在努力成为一名代码简短且干净的程序员。我正在尝试遍历列表中的列表并将其更改为列表中的列表这里是我的代码现在请告诉我是否有任何方法可以实现更短的代码行。

第一,我需要循环遍历列表以更改到目前为止的毫秒,然后我需要循环并向列表中添加键,以便我知道每个值是什么。

import datetime

formatter = ['Date', 'Open', 'Close', 'High', 'Low', 'Volume']
list = [[1364770800000, 93.2, 93.033, 93.29, 92.9, 116.0018], [1364774400000, 93.25, 93.1, 100, 93.03, 345.58388931]]

print(list)

def mili_to_date(d):
    d /= 1000.0
    return datetime.date.fromtimestamp(d).strftime('%Y-%m-%d')


for i, row in enumerate(list):
    for index, column in enumerate(row):
        if index == 0:
            list[i][0] = mili_to_date(column)
        else:
            pass

for i, row in enumerate(list):
    list[i] = {}
    for index, column in enumerate(row):
        list[i][candles_formatter[index]] = column

print(list)

1 个答案:

答案 0 :(得分:2)

成为(更好)程序员:

import datetime as dt
from pprint import pprint # just for formatting

def mili_to_date(d):
    """Uses a time in milliseconds since 1970.1.1 (unix time) and creates a string date"""

    d /= 1000.0
    return dt.date.fromtimestamp(d).strftime('%Y-%m-%d')

def toDict(lis):
    """Secret method to map inner list to keys. Shhh - dont tell no one nothing.

    TODO: Also, when time, implement tests to assure length-equality between mapping and 
    input as well as some error handling if the 'Date' is not a number or something is 
    None. Lenght euqality is important as zip will only work for as much as the shorter
    list is long. If its shorter then length of formatter, some dict keys will not occure.
    Look at itertools.zip_longest() for a zip that fills the shorter lists with defaults."""

    formatter = ['Date', 'Open', 'Close', 'High', 'Low', 'Volume']
    z = zip(formatter,lis) 
    return { key: mili_to_date(val) if key == 'Date' else val for key,val in z}

if __name__ == "__main__": 
    # make me a dictionary
    li = [[1364770800000, 93.2, 93.033, 93.29, 92.9, 116.0018],
          [1364774400000, 93.25, 93.1, 100, 93.03, 345.58388931]]
    L = [toDict(x) for x in li] 
    pprint(L)  

输出:

[{'Close': 93.033,
  'Date': '2013-04-01',
  'High': 93.29,
  'Low': 92.9,
  'Open': 93.2,
  'Volume': 116.0018},
 {'Close': 93.1,
  'Date': '2013-04-01',
  'High': 100,
  'Low': 93.03,
  'Open': 93.25,
  'Volume': 345.58388931}]
相关问题