【问题标题】:Given one list, how do you find where the same values are indexed in a different list?给定一个列表,您如何找到相同值在不同列表中的索引位置?
【发布时间】:2020-03-22 14:11:19
【问题描述】:

我正在为背包算法创建一个解密函数。我是 Python 编程的新手。我需要找到一个数组中的值出现在另一个数组中的位置,索引这些值,将索引值设置为“1”,并将另一个列表中没有等效值的其他值设置为“0”。

假设:

privkey = [2,3,6,13,27,52]
searchList = [3,6]

由于 searchList 中的 [3,6] 出现在位置 privkey[1] 和 privkey[2] 我希望代码将这些索引设置为新列表中的二进制“1”。所以新的值应该是 newList= [0,1,1,0,0,0]。

到目前为止我尝试过的是:

newList = []
for i in privkey:
if (privkey[i]==searchList[i]):
    newList = append(privkey.index(i)) # should yield newList = [1,2]  
    print(newList)
else:
    print("none")

我真的不知道如何使用索引将 privkey 中的值设置为“1”值。任何帮助将不胜感激。谢谢。

【问题讨论】:

    标签: python list encryption indexing knapsack-problem


    【解决方案1】:

    您可以通过列表理解来做到这一点:

    >>> privkey = [2,3,6,13,27,52]
    >>> searchList = [3,6]
    >>> [int(x in searchList) for x in privkey]
    [0, 1, 1, 0, 0, 0]
    

    https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions

    【讨论】:

      【解决方案2】:

      有一个使用列表推导的简单解决方案,但由于它需要对searchList 进行许多成员资格测试,因此您应该首先创建一个集合:

      >>> search_set = set(searchList)
      >>> [ int(x in search_set) for x in privkey ]
      [0, 1, 1, 0, 0, 0]
      

      测试 x in search_set 返回一个布尔值,使用 int 函数将其转换为 1 或 0。

      如果privkey 的长度为 m,searchList 的长度为 n,则此解决方案在 O(m + n) 时间内运行并使用 O(m + n) 空间。没有集合的解决方案是 O(mn) 时间和 O(m) 空间,对于较大的输入,这将相当慢。

      【讨论】:

        猜你喜欢
        • 2021-12-27
        • 1970-01-01
        • 2019-07-13
        • 2021-04-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多