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

Hi I'm trying to become a better programmer with short and clean code. I'm trying to loop through a list in a list and change it to dictionary inside a list here is my code right now please show me if there is anyway to achieve is with shorter lines of code.

1st I need to loop through the list to change the miliseconds to date and then I need to loop through and add keys to the list so that I know what each value is.

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)

解决方案

To be(-come) a better programmer:

document your functions

embrace error handling and think about which errors might happen for creative input

do not use names of built-in or datatypes like set/list/dict/tuple/... as variable names

leverage the power of built-ins - like zip():

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)

Output:

[{'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}]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值