【问题标题】:Combining two lists, only keep similar values, python [duplicate]结合两个列表,只保留相似的值,python [重复]
【发布时间】:2020-08-11 10:54:42
【问题描述】:
x=[1,3,5,8]
y=[2,4,5,8]

z=[5,8]

如何将列表 x 和 y 组合到列表 z 中,其中仅给出 x AND y 中存在的值?

感谢您的帮助

【问题讨论】:

    标签: python-3.x


    【解决方案1】:

    你可以这样做

    x = [1, 3, 5, 8]
    y = [2, 4, 5, 8]
    
    z = [k for k in y if k in x]
    

    【讨论】:

    • 也可以建议内置函数set.intersection(*s)。
    【解决方案2】:

    这里是解决方案-

    # Initialisation of first list 
    list1 = [1,3,5,8] 
    
    # Initialisation of Second list 
    list2 = [2,4,5,8]
    
    output = [i for i in list2 if i in list1]
    
    # printing result 
    print(output) 
    

    【讨论】:

      猜你喜欢
      • 2016-07-31
      • 2023-02-22
      • 2023-03-13
      • 2023-04-04
      • 1970-01-01
      • 2019-12-13
      • 2021-10-29
      • 2018-09-01
      • 1970-01-01
      相关资源
      最近更新 更多