其他分享
首页 > 其他分享> > 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))

 

标签:tuple,number,lists,35,2022,number1,append,两数,numbers
来源: https://www.cnblogs.com/scholarly/p/16542371.html