简体   繁体   中英

Python List comprehension with items() and enumerate()

I would like to implement this:

asset_hist = []
for key_host, val_hist_list in am_output.asset_history.items():
     for index, hist_item in enumerate(val_hist_list):
        row = collections.OrderedDict([("computer_name", key_host), ("id", index), ("hist_item", hist_item)])
        asset_hist.append(row)

Using list comprehension. This is as close as I can get:

asset_hist = [collections.OrderedDict([("computer_name", key_host), ("id", index), ("hist_item", hist_item)]) for index, hist_item in enumerate((val_hist_list, key_host)[0]) for key_host, val_hist_list in am_output.asset_history.items()]

You are close:

import collections

asset_hist = [collections.OrderedDict([("computer_name", key_host), ("id", index), ("hist_item", hist_item)]) for index, hist_item in enumerate(val_hist_list) for key_host, val_hist_list in am_output.asset_history.items()]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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