根据Python中的值查找列表中的位置?

时间:2012-03-19 01:06:28

标签: python list position term

我是Python的新手,我正在研究一些新的代码形式。 我在一到二十之间选择了5个随机数,这里有两个列表。像这样。

list = []
listn = []
import random
for i in range(5):
     newvar = random.randomint(1,20)
     list.append(newvar)
     newvart = random.randomint(1,20)
     listn.append(newvart)

然后我在同一代码中选择另一个变量。

evar = random.randomint(1,20)

我想要做的是查看数字是否在两个列表中,如果是,它们是否在列表中的相同位置。我应该通过以下方式开始这个:

if (evar in list) and (evar in listn):

但我不知道如何做其余的事情。我想知道evar是否在两个列表中并且在两个列表中处于相同位置(即它是list和listn中的第三个数字)。我该怎么做?

5 个答案:

答案 0 :(得分:3)

假设使用list.index() method首先找到的位置应该相同:

def f(lst1, lst2, value):
    try: return lst1.index(value) == lst2.index(value)
    except ValueError:
        return False

使用set intersection允许所有职位:

def positions(lst, value):
    return (pos for pos, x in enumerate(lst) if x == value)

def f(lst1, lst2, value):
    return bool(set(positions(lst1, value)).intersection(positions(lst2, value)))

甚至更好:@wim建议的基于zip()的解决方案:

from itertools import izip

def f(lst1, lst2, value):
    return any(x1 == x2 == value for x1, x2 in izip(lst1, lst2))

注意:any()会在找到第一个True项后立即返回,而不会不必要地枚举其余项目。

答案 1 :(得分:2)

编辑 这是一个单行的基本想法,由JF在下面的评论中发布:

any(x1 == x2 == evar for x1, x2 in zip(list1, list2))


>>> def foo(list1, list2, evar):
...   for x1, x2 in zip(list1, list2):
...     if x1 == x2 == evar:
...       return True
...   else:
...     return False
... 
>>> foo([1, 2, 69, 3], [3, 4, 69, 5], 69)
True
>>> foo([1, 2, 69, 3], [3, 4, 69, 5], 3)
False
>>> foo([1, 2, 2, 3], [3, 4, 2, 5], 2)
True

以下是一些额外提示:

  • 应避免使用list作为变量名称,因为它会影响内置函数。
  • 没有random.randomint,我想你的意思是random.randint
  • 生成随机列表可以很好地使用列表理解而不是循环,如下所示:[random.randint(1, 20) for _ in xrange(5)]

答案 2 :(得分:1)

如果你需要知道匹配发生的索引,你可以使用类似的东西

try:
    idx = next(i for i,x in enumerate(list1) if evar==x==list2[i])
    ...
except StopIteration:
    # not found
    ...

或更简单地使用J.F. Sebastian的建议

idx = next((i for i,x in enumerate(list1) if evar==x==list2[i]), -1)
如果没有匹配,

将返回-1

答案 3 :(得分:0)

if (evar in list):
    if (evar2 in listn):
        if (evar == evar2 and list.index(evar2) == listn.index(evar2):
            do_something()

答案 4 :(得分:0)

Python在这些方面非常简单,它非常容易处理。只需使用list.index(var),它返回列表中var的索引。

from random import randint 
list1 = []
list2 = []
for i in range(5):
    list1.append(randint(1,20))
    list2.append(randint(1,20))
evan = randint(1,20) 
if (evan in list1 and evan in list 2) and (list1.index(evan) == list2.index(evan)):
    print 'They are at the same place'.