【问题标题】:string with values selection based on values [closed]基于值选择值的字符串[关闭]
【发布时间】:2017-12-09 19:19:15
【问题描述】:

我有一个包含 2 个值的集合

list = [('coin unit', 9.0), ('normal margin requirements', 8.5), ('futures industry', 8.2), ('wild cryptocurrency market', 7.333333333333334), ('biggest financial institutions', 6.833333333333334), ('futures market', 1.0), ('biggest banks', 0.5), ('cryptocurrency frenzy', 0.5)]

我怎样才能只保留那些得分大于 1 的值?

【问题讨论】:

  • 使用list comprehension l = [(a, b) for a, b in l if b > 1]
  • 感谢@PatrickHaugh!不知道这个术语!

标签: python list selection


【解决方案1】:
list_of_stuff = [('coin unit', 9.0), ('normal margin requirements', 8.5), ('futures industry', 8.2), ('wild cryptocurrency market', 7.333333333333334), ('biggest financial institutions', 6.833333333333334), ('futures market', 1.0), ('biggest banks', 0.5), ('cryptocurrency frenzy', 0.5)]
newlist = [x for x in list_of_stuff if x[1] > 1.0]
print newlist

将导致

[('coin unit', 9.0), ('normal margin requirements', 8.5), ('futures industry', 8.2), ('wild cryptocurrency market', 7.333333333333334), ('biggest financial institutions', 6.833333333333334)]

【讨论】:

    【解决方案2】:

    没有循环怎么办:

    list_1 = [('coin unit', 9.0), ('normal margin requirements', 8.5), ('futures industry', 8.2), ('wild cryptocurrency market', 7.333333333333334), ('biggest financial institutions', 6.833333333333334), ('futures market', 1.0), ('biggest banks', 0.5), ('cryptocurrency frenzy', 0.5)]
    
    print(list(filter(lambda x:x[1]>1,list_1)))
    

    输出:

    [('coin unit', 9.0), ('normal margin requirements', 8.5), ('futures industry', 8.2), ('wild cryptocurrency market', 7.333333333333334), ('biggest financial institutions', 6.833333333333334)]
    

    P.S:永远不要使用list作为变量名,因为list是python中的关键字。

    【讨论】:

    • 我同意,但我使用的是他的变量,应该修复它...并做到了:-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-28
    • 1970-01-01
    • 2021-03-22
    • 1970-01-01
    • 1970-01-01
    • 2013-06-16
    相关资源
    最近更新 更多