【问题标题】:How to compare lists in Python如何在 Python 中比较列表
【发布时间】:2016-03-03 13:37:45
【问题描述】:

如果我有 3 个这样的列表:

general_list = ['P' ,      'J' ,   'C',   'H' ,     'O']

real_list    = ['Python', 'Java' , 'C' , 'Html' , 'Other']

还有一个叫做

的列表
selected_items = [ 'Python' , 'Php']

我想将selected_itemsreal_list 进行比较,这样当元素在列表中时,我可以得到一个结果,放入0 or 1, 所以我想做这样的事情:[ 1 , 0 , 0, 0 , 1] 然后检查何时选择了 general_list 中的项目并得到这样的结果['P' , 'O']

我真的不知道该怎么做?

【问题讨论】:

  • 到目前为止有什么尝试?
  • 应该试一试吗?..铅笔和纸会是一个好的开始吗?
  • @MSeifert 我只是不知道从哪里开始,所以我问任何想法,因为我不希望有人为我编码,而只是给我一个提示

标签: python list dictionary


【解决方案1】:

似乎是XY problem。如果你真正想要的是使用selected_items得到最终结果,那么:

this_is_useful = {'Python': 'P', 'Java': 'J', 'C': 'C', 'Html': 'H'}

然后你可以通过做检查'Python'是否属于

if 'Python' in this_is_useful:
    print "Yes!"

要获得最终结果:

selected_items = [ 'Python' , 'Php' ]
result = [this_is_useful.get(l, 'O') for l in selected_items]

【讨论】:

    【解决方案2】:

    您可以使用两个列表推导来做到这一点:

    inlist = [True if x in selected_items else False for x in real_list]
    result = [v for i, v in enumerate(general_list) if inlist[i]]
    

    【讨论】:

      猜你喜欢
      • 2021-01-19
      • 2015-04-30
      • 1970-01-01
      • 2017-03-12
      • 1970-01-01
      • 2011-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多