【问题标题】:combining two lists into a new list and sorting将两个列表组合成一个新列表并排序
【发布时间】:2011-09-26 11:31:57
【问题描述】:
shares_1 = [50, 100, 75, 200]
shares_2 = [100, 100, 300, 500]
shares_1.extend(shares_2)
print shares_1

输出 [50, 100, 75, 200, 100, 100, 300, 500]

我想要的是为合并列表分配一个变量并对列表进行排序。看看我下面的错误尝试有什么建议吗?

shares_3.sort() = shares_1.extend(shares_2)

谢谢!

【问题讨论】:

    标签: python list sorting merge


    【解决方案1】:

    Josh Matthews' 回答提供了两种好方法。不过,这里有一些一般原则需要理解:首先,通常,当您调用更改列表的方法时,它也不会返回更改后的列表。所以...

    >>> shares_1 = [50, 100, 75, 200]
    >>> shares_2 = [100, 100, 300, 500]
    >>> print shares_1.extend(shares_2)
    None
    >>> print shares_1.sort()
    None
    

    如您所见,这些方法不返回任何内容——它们只是改变了它们所绑定的列表。另一方面,您可以使用sorted,它不会更改列表,而是复制它,对副本进行排序,然后返回副本:

    >>> shares_1.extend(shares_2)
    >>> shares_3 = sorted(shares_1)
    >>> shares_3
    [50, 75, 100, 100, 100, 100, 100, 200, 300, 300, 500, 500]
    

    其次,请注意您可以永远分配给函数调用。

    >>> def foo():
    ...     pass
    ... 
    >>> foo() = 1
      File "<stdin>", line 1
    SyntaxError: can't assign to function call
    

    【讨论】:

      【解决方案2】:
      shares_3 = sorted(shares_1 + shares_2)
      

      【讨论】:

        【解决方案3】:
        shares_3 = shares_1 + shares_2
        shares_3.sort()
        

        或者,

        shares_1.extend(shares_2)
        shares_1.sort()
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-11-10
          • 2023-02-18
          • 2015-05-12
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多