【问题标题】:How to print a python list, minus a specific element?如何打印一个python列表,减去一个特定的元素?
【发布时间】:2016-11-18 21:15:44
【问题描述】:

给定:

commands = dict(
   onboarding = dict(
      default = "default",
      status = "APPROVED",
      date = "11/18/15"
   )
   team = dict(
       members = getTeamMembers()
)  

我该怎么做

print commands['onboarding'].keys() 

不打印列表中的“默认”键?我试图在我的实现中隐藏它。如果在两个版本的 python 中都有解释,则加分。

谢谢!

【问题讨论】:

    标签: python python-2.7 list python-3.x


    【解决方案1】:
    print [key for key in commands['onboarding'] if key != 'default']
    

    【讨论】:

    • 我的男人!谢谢你。已经环顾了几个小时,非常感谢快速响应。
    【解决方案2】:

    如果您from __future__ import print_function,您可以在两个版本中使用以下内容:

    d=commands['onboarding']
    print(*[d[i] for i in d if i != 'default'])
    

    您从所有适用的密钥构建一个列表并在 print 调用中解压缩。当然,如果您需要输出中的列表,请不要解压缩(即从列表理解的开头删除 *)。

    【讨论】:

      【解决方案3】:

      你也可以像 Python 2.7 一样使用filter

      print filter(lambda key: key != 'default', commands['onboarding'])
      

      或者在 Python 3 中像这样

      print(list(filter(lambda key: key != 'default', commands['onboarding'])))
      

      在 Python 3 中,filter 返回一个可迭代的 filter 对象,而不是 Python 2 中的列表,因此您必须将其包装在 list()

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-10-15
        • 1970-01-01
        • 1970-01-01
        • 2019-01-08
        • 2022-11-02
        • 1970-01-01
        • 1970-01-01
        • 2021-12-01
        相关资源
        最近更新 更多