【问题标题】:python append list return nonepython追加列表返回无
【发布时间】:2014-01-20 20:50:17
【问题描述】:

我有以下代码来生成元组列表:

list_of_tuples = list()

for name in list_of_names:
    temporary_list = [name]
    date = function_that_return_a_list      #like ['2014', '01', '20']
    temporary_list = temporary_list + date
    print temporary_list    #returns the correct list of [name, '2014', '01', '20']
    list_of_tuples.append(temporary_list)     #crashes with the error message "TypeError: append() takes exactly one argument (0 given)"

print flist

问题似乎与我尝试在日期列表中使用它们时 append 和 insert 函数返回 None 有关

【问题讨论】:

  • 当你这样做时会发生什么:list_of_tuples.append(tuple(temporary_list))
  • 您能否提供一个可运行的SSCE 来重现该问题?
  • 您的代码 sn-p 不会对我产生错误(将 function_that_return_a_list 替换为 ['2014', '01', '20'] 时),错误消息也没有意义。您能否a)向我们提供异常的完整回溯和b)实际产生异常的代码示例?
  • 您提供的代码不会产生任何错误。请提供代码示例...
  • @user2856110:描述符?那你没有打电话list()

标签: python python-2.7


【解决方案1】:

您忘记调用 list() 类型:

list_of_tuples = list()
#    ----------------^ You didn't do this.

您的异常(如 cmets 中所述)表明您尝试在类型对象上调用 .append

>>> list.append(())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: descriptor 'append' requires a 'list' object but received a 'tuple'
>>> list().append(())

在任何情况下最好使用[] 来生成一个空列表:

list_of_tuples = []

【讨论】:

    猜你喜欢
    • 2010-12-27
    • 2015-03-22
    • 2019-08-26
    • 1970-01-01
    • 2020-12-02
    • 2012-08-30
    • 2014-01-30
    • 2018-05-12
    • 1970-01-01
    相关资源
    最近更新 更多