繁体   English   中英

如何添加到列表元组对

[英]How to add onto a list tuple pairs

给定一个数字列表和一个数字 k,返回列表中的任意两个数字加起来是否为 k。

例如,给定 [10, 15, 3, 7] 和 17 的 k,返回 true,因为 10 + 7 是 17。

代码:

numbers = [6, 7, 8, 3]
k = 14

def add_to_k(numbers_list,k_value):
    truth = False
    pairs = []
    for i in numbers_list:
        for l in numbers_list:
            added = i + l
            if added == k_value:
                if numbers_list.index(i) == numbers_list.index(l):
                    pass
                else:
                    paired = str(i) + ", " + str(l)
                    pairs += paired
                    truth = True
    if truth == True:
        print("Two numbers in the list added together is {}: ".format(k_value) + str(pairs))
    else:
        print("Sorry, none give " + str(k_value))
add_to_k(numbers,k)

此代码返回 output,如下所示:

Two numbers in the list added together is 17: ['6', ',', ' ', '8', '8', ',', ' ', '6']

但我希望它给我在元组中加到 17 的两个数字。 例如,[(1,2),(3,4)]

您应该 append paired的值在下面的代码中已更改

numbers = [6, 7, 8, 3]
k = 14


def add_to_k(numbers_list,k_value):
    truth = False
    pairs = []
    for i in numbers_list:
        for l in numbers_list:
            added = i + l
            if added == k_value:
                if numbers_list.index(i) == numbers_list.index(l):
                    pass
                else:
                    ## modification done here
                    paired = (i,l)
                    pairs.append(paired)
                    ## modification end
                    truth = True
    if truth == True:
        print("Two numbers in the list added together is 17: " + str(pairs))
    else:
        print("Sorry, none give " + str(k_value))
add_to_k(numbers,k)

output:

Two numbers in the list added together is 17: [(6, 8), (8, 6)]

使用itertools不同方法

import itertools

选项 1:如果要生成唯一的数字集,则使用itertools.combinations

combinations = list(itertools.combinations(numbers, 2))

选项 2:如果要生成所有数字组合集,则使用itertools.permutations

combinations = list(itertools.permutations(numbers,2))

然后检查值的总和到k

output = [comb for comb in combinations if comb[0]+comb[1] == k]
output

选项 1: output 使用itertools.combinations

[(6, 8)]  

选项 2: output 使用itertools.permutations

[(6, 8),(8, 6)]

列表理解应该起作用。

li = [10, 15, 3, 7]
k=14

res = k in [a+b for a in li for b in li] 

print (res)

Output:

True

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM