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

标签 python list

我正在研究一些新的代码形式。 我在两个列表中选择了 1 到 20 之间的 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 中的第三个数字)。我该怎么做?

最佳答案

假设使用 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 项目就返回,而无需不必要地枚举其余项目。

关于python - 根据 Python 中的值在列表中查找位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9763818/

相关文章:

python - 按标签选择的 Pandas 有时会返回 Series,有时会返回 DataFrame

python - 使用 Python 脚本包装在 Bash-Shell 中输入的所有命令

python - 安全的 Python Markdown 库

javascript - 将 List 类型的参数传递给 Javascript 函数

python - 如何将 APScheduler JobStore 与 SQLAlchemy 模型(外键)相关联 - Python Flask

python - 将 Django 模型属性名称传递给函数

python - 使用python将字符串转换为格式

python - JSON或Python dict/list解码问题

Python:os.system 的输入被拆分

python - 查找列表中缺失的元素