【问题标题】:Tuple, List Python operations元组,列出 Python 操作
【发布时间】:2020-12-23 10:13:53
【问题描述】:
def subtract_months(input_list):
    output_list = []
    
    #TODO: implement your code here
    new_list = [item for sublist in input_list for item in sublist]
    #print(flat_list)
        
    for i in range(len(new_list)):
        if new_list[i][2] > new_list[i][1]:
            new_list[i][2] = new_list[i][1] - new_list[i][2]
      
    
input_list = [[(2000,1,14),(2020,5,3)]]
subtract_months(input_list)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-178-26dd75c8bd92> in <module>
     19 
     20 input_list = [[(2000,1,14),(2020,5,3)]]
---> 21 subtract_months(input_list)

<ipython-input-178-26dd75c8bd92> in subtract_months(input_list)
      9         print(i)
     10         if new_list[i][2] > new_list[i][1]:
---> 11             new_list[i][2] = new_list[i][1] - new_list[i][2]
     12 
     13 

TypeError: 'tuple' object does not support item assignment

我知道元组是不可变的,因此,我将它们转换为一个列表,但我得到了同样的错误,即“元组”对象不支持项目分配。 我想更新元素本身的值。 例如:(2000,1,14) ->> (2000,12,-13)。 我在几年和几个月内执行更改。在上面的示例中,2000 是一年,1 是月份,我想从 1 中减去 14 并相应地更新年份和月份。 注意:我不想使用 datetime.timedelta()。

谢谢

【问题讨论】:

  • 你能举出更多的例子吗?在您的示例中,年份不应该从 2000 年变为 1999 年吗?
  • 提示:创建“new_list”后执行“print(repr(new_list))”查看你创建的内容。
  • @angelogro 是的,因此年份也应该改变,我写的年份和月份应该相应地改变。
  • @MichaelButscher [(2000, 1, 14), (2020, 5, 3)]。这是 print(repr(new_list)) 的输出。

标签: python list date time tuples


【解决方案1】:

我不确定你到底想做什么,但错误是一致的。

new_list = [item for sublist in input_list for item in sublist]

试试下面的代码,如果你能更清楚地发布你的要求,它应该可以工作,这样更容易理解和回答。

def subtract_months(input_list):
    output_list = []
    
    #TODO: implement your code here
    new_list = [list(item) for sublist in input_list for item in sublist]
    print(new_list)
    
        
    for i in range(len(new_list)):
        if new_list[i][2] > new_list[i][1]:
            new_list[i][2] = new_list[i][1] - new_list[i][2]
    
    return new_list
      
    
input_list = [[(2000,1,14),(2020,5,3)]]
print(subtract_months(input_list))

【讨论】:

    【解决方案2】:

    改变这个

    input_list = [[(2000,1,14),(2020,5,3)]]
    

    input_list = [[[2000,1,14],[2020,5,3]]]
    

    元组在 Python 中是不可变的。您可以向其中添加元素,但不能修改其内部的内容。

    【讨论】:

      【解决方案3】:

      你不能用元组做赋值,它们是不可变的,你只能用列表,所以你可以改变这一行:

      input_list = [[(2000,1,14),(2020,5,3)]]
      

      收件人:

      input_list = [[[2000,1,14],[2020,5,3]]]
      

      【讨论】:

        【解决方案4】:

        new_list 是一个元组列表。 new_list[i][2] = ... 分配给元组 which is not allowed 的一个项目。因此出现错误消息。

        要修复您的代码,请使用列表(请参阅 U11-Forward 的答案)或构造新元组而不是尝试操作它们。

        【讨论】:

          猜你喜欢
          • 2017-04-05
          • 1970-01-01
          • 2018-02-25
          • 2012-06-30
          • 2016-06-03
          • 2010-10-04
          • 2012-06-06
          • 2023-03-18
          • 2022-01-03
          相关资源
          最近更新 更多