Java教程

2022_lesson_35 找出列表中两数之和为特殊值

本文主要是介绍2022_lesson_35 找出列表中两数之和为特殊值,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
 1 """
 2 找出列表中两数之和为特殊值,比如8的组合
 3 """
 4 number_lists = []
 5 numbers = [2, 3, 5, 8, 7, 4, 1, 6]
 6 for number in numbers:
 7     for number1 in numbers:
 8         if number+number1 == 8:
 9             number_tuple = number,number1
10             number_tuple1 = number1,number
11             if number_tuple and number_tuple1 not in number_lists:
12                 number_lists.append(number_tuple)
13 print(number_lists)

改进

1 for number in numbers:
2     for number1 in numbers:
3         if number+number1 == 8 and (number,number1) not in number_lists and (number1,number) not in number_lists :
4                 number_lists.append((number,number1))
5 print(number_lists)

这里的列表的append元组,用法很新颖

number_lists.append((number,number1))

 

这篇关于2022_lesson_35 找出列表中两数之和为特殊值的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!