【问题标题】:Python utilizing split listsPython 利用拆分列表
【发布时间】:2013-02-01 21:32:53
【问题描述】:

如何在 Python 中使用列表的第二部分?

例如,列表包含一个字符串和整数:

('helloWorld', 20)
('byeWorld', 10)
('helloagainWorld', 100)

我希望在列表的第二部分(整数)上创建一个 if 语句,最好不要创建一个新列表来存储整数。这可能吗?

【问题讨论】:

    标签: python list if-statement split tuples


    【解决方案1】:

    只使用索引

    >>> a = ('helloWorld', 20)
    >>> a[1]
    20
    >>> 
    

    【讨论】:

      【解决方案2】:

      使用索引:

      >>> a = (1,2)
      >>> a[0]
      1
      >>> a[1]
      2
      

      【讨论】:

        【解决方案3】:

        您可以使用函数来获取tuple 的第二个元素或使用operator.itemgetter 之类的东西,这是该文档中给出的示例:

        >>> inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)]
        >>> getcount = itemgetter(1)
        >>> map(getcount, inventory)
        [3, 2, 5, 1]
        >>> sorted(inventory, key=getcount)
        [('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)]
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-02-25
          • 2013-02-25
          相关资源
          最近更新 更多