Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 在Python中计算相加为特定值的数对_Python 3.x - Fatal编程技术网

Python 3.x 在Python中计算相加为特定值的数对

Python 3.x 在Python中计算相加为特定值的数对,python-3.x,Python 3.x,我想计算一个列表中有多少对数字可以添加到一个特定的数字中,这是我用python编写的代码,但输出不是它应该的结果 list = [1,2,3,4] x=3 count = 0 for i in range(len(list)): for j in range(len(list)): if i + j == x: count+=1 print(count) 您的代码有一些问题: 一是它从不直接引用列表中的项目。因此,它将只在假设列表中的数字是升序的情况下工作,每个数字相隔一个,并且从1开始。 另

我想计算一个列表中有多少对数字可以添加到一个特定的数字中,这是我用python编写的代码,但输出不是它应该的结果

list = [1,2,3,4]
x=3
count = 0
for i in range(len(list)):
for j in range(len(list)):
if i + j == x:
count+=1
print(count)
您的代码有一些问题: 一是它从不直接引用列表中的项目。因此,它将只在假设列表中的数字是升序的情况下工作,每个数字相隔一个,并且从1开始。 另一个原因是,它对数字对进行了多次迭代。 最后,还有一些缩进问题,但我猜这些问题只是在复制粘贴中丢失的。我试图重新缩进它,但当我运行它时,我得到了“4”,当它应该是“1”。 下面是一个包含索引列表的版本,它应该可以解决上述问题

list = [1,2,3,4]
x = 3
count = 0
for i in range(0,len(list)):
    pair1 = list[i]
    pair2 = list[i+1:]
    for j in range(0,len(pair2)):
        if pair1 + pair2[j] == x:
            count += 1
print(count)

您可以使用中的函数简化代码,具体取决于您希望迭代列表的方式,即组合、替换组合或产品

import itertools as itt

in_list = [1,2,3,4]
tgt_num = 3
count = 0
for a,b in itt.combinations(in_list, 2): # returns 1
# for a,b in itt.combinations_with_replacement(in_list, 2): # returns 1
# for a,b in itt.product(in_list, in_list): # returns 2
    if a + b == tgt_num:
            count += 1
print(count)

请正确缩进代码,并显示您得到的答案和期望值。