Warm tip: This article is reproduced from serverfault.com, please click

python-无法将元组插入列表

(python - Can't insert tuple into a list)

发布于 2020-11-28 11:52:08

我想在列表中插入一个日期对象。但是,在执行时,代码会引发TypeError。这是代码:

values.append(datetime.date(tuple(checkIn)))
values.append(datetime.date(tuple(checkOut)))

为了给观众带来愉悦感,我仅提供了引发错误的代码行。

这里,

  • values 是一个清单
  • checkIncheckOut是列表。例如- checkIn = [2020, 11, 28]

这是错误消息:

File "d:/coding/python/hms.py", line 195, in booking
    values.append(dt.date(tuple(checkIn)))
TypeError: an integer is required (got type tuple)

那么,为什么不能在列表中插入元组?

Questioner
Shounak
Viewed
0
Maurice Meyer 2020-11-28 19:58:19

你需要解包, checkIn然后checkOut才能将值作为参数传递:

import datetime as dt

values = []
checkIn = [2020, 11, 28]

values.append(dt.date(*checkIn))
print(values)

出去:

[datetime.date(2020, 11, 28)]