Jas*_*von 6 python loops for-loop
我有一个整数列表,我通过for循环运行,以发现两个元素组合是否等于另一个变量t.所以如果t等于10并且我有一个整数列表:
l = [1,2,3,4,5,8,9]那么该函数应该打印所有不同的数字组合(1,9),(2,8).
我觉得我差不多了,但是当我使用这个.pop()功能时,列表中发生了一些奇怪的事情.下面的代码用于显示需要计算的所有数字组合,但会跳过列表中的每个其他元素.
l = [1,2,5,8,13,15,26,38]
c = 10
for i in l:
first = i
l.pop(0)
for x in l:
second = x
print(first,second)
Run Code Online (Sandbox Code Playgroud)
这是输出:
1 2
1 5
1 8
1 13
1 15
1 26
1 38
5 5
5 8
5 13
5 15
5 26
5 38
13 8
13 13
13 15
13 26
13 38
26 13
26 15
26 26
26 38
Run Code Online (Sandbox Code Playgroud)
请注意如何2,8,15,和38被跳过.我正在使用,l.pop以便第二个for循环不会使用原始值,然后下一个迭代可以继续迭代列表中的下一个元素.
您正在尝试执行的操作将无法正常工作,因为您在迭代时正在修改列表.假设当前"指针"指向第一个元素.现在你弹出第一个,所以指针在第二个.但是当循环前进时,指针移动到第三个,第二个被跳过.
您似乎想要从列表中找到组合.您还可以尝试其他一些方法:
最接近当前的方法:使用while循环而不是for循环
while l:
first = l.pop(0)
for second in l:
print(first, second)
Run Code Online (Sandbox Code Playgroud)或者您可以只迭代索引而不是列表本身:
for i in range(len(l)):
for k in range(i+1, len(l)):
print(l[i], l[k])
Run Code Online (Sandbox Code Playgroud)或者只是使用 itertools.combinations
import itertools
for first, second in itertools.combinations(l, 2):
print(first, second)
Run Code Online (Sandbox Code Playgroud)但是,你可以做得更好.由于您正在寻找一对加起来某个目标数的数字,因此只需从目标中减去第一个以得到第二个数字,然后查看第二个数字是否在数字列表中.使用a set可以在恒定时间内进行此查找,从而将总时间复杂度从O(n²)降低到O(n).
numbers = set([1,2,5,8,13,15,26,38])
target = 10
for first in numbers:
second = target - first
if second > first and second in numbers:
print(first, second)
Run Code Online (Sandbox Code Playgroud)