gpt4 book ai didi

python - 如何改进评估列表以确定其是否包含特定连续项目的方法?

转载 作者:太空宇宙 更新时间:2023-11-03 21:06:44 26 4
gpt4 key购买 nike

我有一个包含数千万个列表的嵌套列表(我也可以使用元组)。每个列表有 2-7 个项目长。列表中的每个项目都是 1-5 个字符的字符串,并且每个列表中出现的次数不超过一次。 (为了简单起见,我在下面的示例中使用单个字符项)

#Example nestedList: 

nestedList = [
['a', 'e', 'O', 'I', 'g', 's'],
['w', 'I', 'u', 'O', 's', 'g'],
['e', 'z', 's', 'I', 'O', 'g']
]

我需要找到嵌套列表中的哪些列表包含一对项目,以便我可以对这些列表执行操作,同时忽略其余列表。这需要尽可能高效。

我正在使用以下函数,但它看起来相当慢,我只是知道必须有一种更智能的方法来做到这一点。

def isBadInList(bad, checkThisList):
numChecks = len(list) - 1
for x in range(numChecks):
if checkThisList[x] == bad[0] and checkThisList[x + 1] == bad[1]:
return True
elif checkThisList[x] == bad[1] and checkThisList[x + 1] == bad[0]:
return True
return False

我会这样做,

bad = ['O', 'I']

for checkThisList in nestedLists:
result = isBadInList(bad, checkThisList)
if result:
doStuffToList(checkThisList)

#The function isBadInList() only returns true for the first and third list in nestedList and false for all else.

如果可能的话,我需要一种更快地完成此操作的方法。我可以使用元组而不是列表,或者任何需要的东西。

最佳答案

nestedList = [
['a', 'e', 'O', 'I', 'g', 's'],
['w', 'I', 'u', 'O', 's', 'g'],
['e', 'z', 's', 'I', 'O', 'g']
]

#first create a map
pairdict = dict()


for i in range(len(nestedList)):
for j in range(len(nestedList[i])-1):
pair1 = (nestedList[i][j],nestedList[i][j+1])
if pair1 in pairdict:
pairdict[pair1].append(i+1)
else:
pairdict[pair1] = [i+1]
pair2 = (nestedList[i][j+1],nestedList[i][j])
if pair2 in pairdict:
pairdict[pair2].append(i+1)
else:
pairdict[pair2] = [i+1]

del nestedList

print(pairdict.get(('e','z'),None))

创建一个值对并将它们存储到映射中,键是对,值是索引,然后删除您的列表(这可能会占用太多内存),然后,您可以利用字典进行查找,并打印该值出现的索引。

关于python - 如何改进评估列表以确定其是否包含特定连续项目的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55348688/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com