从python中的列表中选择唯一对

时间:2016-10-27 19:06:02

标签: python python-2.7 python-3.x ipython

问题是: 您将获得一个正整数的排序数组和一个数字' X'。打印出总和等于X的所有数字对。打印出唯一的对,并且对应按升序排列。

Sub LastSaturdayIntExtMissTime()
'gets the past Saturday's date based on today.

    Dim iWeekday As Integer, LastSaturdayDate As Date, sfx As String

    iWeekday = Weekday(Now(), vbSaturday)
    LastSaturdayDate = Format(Now - (iWeekday - 1), "mm/dd/yyyy")

Select Case Right(Day(LastSaturdayDate), 1)

Case "1"
    sfx = """st"""
Case "2"
    sfx = """nd"""
Case "3"
    sfx = """rd"""
Case Else
    sfx = """th"""
End Select
ActiveWorkbook.Sheets(2).Name = (UCase(Format(Date, "mmm")) & " Data through " & Format(LastSaturdayDate, "mmm d" & sfx)   'this throws a compile error
MsgBox Format(LastSaturdayDate, "mmm d" & sfx)    'this works

End Sub

到目前为止我的代码:

input is: 1,2,3,4,6;5
output should be : 1,4;2,3

我得到的输出是:

with open('/tmp/values.txt') as f:
    for numbers in f:
    num_list,sum_list = [  num.split(",")  for num in numbers.rstrip().split(";")]
sum_list = list(map(int,sum_list))
op1 = [(num_list[i],num_list[j]) for i in range(0,len(num_list)) for j in range(0,len(num_list)) if (eval(num_list[i])+eval(num_list[j]) == sum_list[0])]
print (op1)

任何人都可以帮助我选择逻辑(' 1',' 4')和(' 2',' 3' )从上面的列表?

2 个答案:

答案 0 :(得分:1)

由于加法是可交换的,因此您无需检查两次:

with open('/tmp/values.txt') as f:
    for numbers in f:
        num_list, sum_list = [num.split(",") for num in numbers.rstrip().split(";")]

        sum_list = list(map(int, sum_list))
        op1 = [(num_list[i], num_list[j]) for i in range(len(num_list)) for j in range(i+1, len(num_list)) if (int(num_list[i]) + int(num_list[j]) == sum_list[0])]
        print(op1)

有一个O(n)解决方案(我将留给读者作为练习。)

答案 1 :(得分:0)

做两个嵌套循环时有一个巧妙的技巧。如果您不想要第二个列表中的所有内容,请执行以下操作:

for i in range(0, 5):
    for j in range (i+1, 5):
        print str(i)+", "+str(j)

这导致:

0, 1
0, 2
0, 3
0, 4
1, 2
1, 3
1, 4
2, 3
2, 4
3, 4

这可以确保您不会一次又一次地循环使用相同的数字。这种事情告诉第二个循环不要在第一个循环的同一个地方开始,而只是从它尚未到达的数字开始。 (如果您希望获得0, 01, 1等双打,只需在+1之后取出i

你的代码中有

,你有两个循环:

for i in range(0,len(num_list)) for j in range(0,len(num_list))

您可以将第二个循环更改为:

for j in range(i+1,len(num_list))