优化多个for循环

2024-04-19 07:55:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python新手,目前正在解决一些问题以提高我的编码技能。我遇到了一个问题,我需要在python中从3Lists中找到公共元素并打印公共元素的数量。你知道吗

我的代码和程序如下:

print "Enter n: "
n = raw_input()
print "Enter the values: "
nlist = map(int, raw_input().split())
print "Enter m: "
m = raw_input()
print "Enter the values: "
mlist = map(int, raw_input().split())
print "Enter k: "
k = raw_input()
print "Enter the values: "
klist = map(int, raw_input().split())
plist = []
qlist = []

for x in range(0,int(n)):
    for y in range(0,int(m)):
        if (nlist[x]==mlist[y]):
            plist.append(nlist[x])

for z in range(0,int(k)):
    for u in range(0,len(plist)):
        if (klist[z]==plist[u]):
            qlist.append(klist[z])

print len(qlist)

首先,我从前两个Lists - nlist and mlist中找到公共元素并将它们存储在新的List - plist中,然后取第三个List - klist并在Lists - plist and klist中找到公共元素并将它们添加到新的List - qlist中,并找到最后一个List的长度。我在想,如果Lists的长度非常高,比如说4000个循环和两个for循环运行4000次迭代,按照我的理解是很耗时的。那么如何优化这些问题,解决这类问题的更好方法是什么,可以使用什么方法来提高代码的性能,在更短的时间内产生输出。请帮助我理解这一点。提前谢谢。非常感谢你的帮助。你知道吗


Tags: thein元素forinputrawrangelist
3条回答

看看set.intersection

>>> nlist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> mlist = [1, 3, 5, 7, 9]
>>> klist = [1, 4, 7, 10]
>>> set(nlist).intersection(mlist)
{1, 3, 5, 9, 7}
>>> set(nlist).intersection(mlist).intersection(klist)
{1, 7}

在这里使用集合交集似乎是最好的方法。你知道吗

for s in list(set(list1) & set(list2) & set(list3)):
  print s

这将只打印公共元素。你知道吗

如果将列表存储为集合,则它们会丢失顺序,但查找速度会快得多,因此在这种情况下可以这样做。然后您可以使用列表理解来检查是否有任何值在所有3个值中。或者,可以使用“设置交点”(set intersection)来查找每个中的值,这可能会更快。你知道吗

nlist = set(nlist)
mlist = set(mlist)
klist = set(klist)

way1 = [i for i in nlist if i in mlist and i in klist]
way2 = list(nlist & mlist & klist)

相关问题 更多 >