【问题标题】:how to make a relation between two lists of number in python如何在python中的两个数字列表之间建立关系
【发布时间】:2017-08-13 06:53:59
【问题描述】:

具体问题是这样的:

我有two lists,即:

lst1 = [1,2,5,6,7];
lst2 = [11,12,13,14,15];

我想建立这些列表的关系以匹配另一个列表的相应编号,例如1-11,5-13,7-15...,如果我输入[1,5,7],那么它将自动生成[11,13,15]。我是 python 新手,所以我不知道它是否可行,或者有人能给我一些建议或想法,在此先感谢!

【问题讨论】:

    标签: python list relation sublist


    【解决方案1】:

    您可以创建一个字典,其中第一个列表的元素作为键,第二个列表的元素作为值:

    lst1 = [1,2,5,6,7]
    lst2 = [11,12,13,14,15]
    
    dct = dict((a, b) for a, b in zip(lst1, lst2))
    # or even:
    # dct = {a: b for a, b in zip(lst1, lst2)}
    print(dct)  # {1: 11, 2: 12, 5: 13, 6: 14, 7: 15}
    print(dct[1], dct[5], dct[7])  # 11 13 15
    

    【讨论】:

      【解决方案2】:

      如果您所说的“关系”是指一对一的映射,那么也许您应该看看dictionaries。如果您的列表(lst1lst2)始终具有相同的映射长度和顺序,您可能不需要字典映射,只需正确使用索引以及 index method for lists

      【讨论】:

        【解决方案3】:

        dict(zip(lst1, lst2)) 会没事的。

        container = dict(zip(lst1, lst2))
        
        print(container[1], container[5], container[7])
        

        【讨论】:

          【解决方案4】:

          首先 zip 两个列表,然后使用 列表压缩 在列表的输出上使用 if 条件

          >>> lst1 = [1,2,5,6,7]
          
          >>> lst2 = [11,12,13,14,15]
          
          >>> input_lst = [1,2,5]
          
          >>> [d for c,d in zip(lst1,lst2) if c in input_lst]      # first method Zip
          
          >>> [lst2[lst1.index(v)] for v in (lst1) if v in input_lst]  # second mehod using index
          

          输出

          [11, 12, 13]
          

          详情see

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2020-01-17
            • 1970-01-01
            • 2023-03-29
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多