簡體   English   中英

如何在列表列表中運行 for 循環以使用日期時間?

[英]How do you run a for loop in a list of lists to work with datetime?

我有一個列表列表:

[['2020', '05', '20', '22', '24', '16.7929'],
 ['2020', '05', '29', '05', '50', '12.4465'],
 ['2020', '05', '29', '06', '44', '34.1706']]

我想訪問每個元素,以便我可以使用這個 function:

for x in list:
   for a, b, c, d, e, f in x:
       dt.datetime(int(a), int(b), int(c), int(d), int(e), round(float(f)).timestamp()

但是,作為字符串列表,它只解包每個列表的第一個元素(2020)並將其分解為單個字符。 但是,我還了解到,您根本無法遍歷這樣的整數列表。 你怎么做呢?

for x in list:
  dt.datetime(int(x[0]), int(x[1]), int(x[2]), int(x[3]), round(float(x[4])), int(x[5])).timestamp()

在迭代列表時解包列表,無需在解包之前先對其進行迭代

for a, b, c, d, e, f in list:
    dt.datetime(int(a), int(b), int(c), int(d), int(e), int(f)).timestamp()

但是,您的列表中缺少秒數,並且無法轉換為 datetime

我相信for a, b, c, d, e, f in x:解包方式存在一些混淆。

當您for a, b, c, d, e, f in x:編寫時,這被解釋為:對於x中的每個元素,解包到元組(a, b, c, d, e, f)中。

這就是為什么您的 Python 解釋器會嘗試將"2020"分解為(a, b, c, d, e, f)的原因。

您需要的是:對於list中的每個元素,解壓縮到元組(a, b, c, d, e, f)中,轉換為:

for a, b, c, d, e, f in list:
    dt.datetime(int(a), int(b), int(c), int(d), int(e), int(f)).timestamp()

此外,正如其他人所提到的,您的代碼還有更多問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM