Home > Mobile >  How to pair values from a list
How to pair values from a list

Time:11-07

I am trying to pair the first and last values together from a list, the second and the 2nd last number and so on. I can do it manually:

list = [ slist[0], slist[-1] ]
list1 = [ slist[1], slist[-2] ]

but the problem for me here is that I am taking an input for the number of students and I dont know how many values the list contains and im trying to find an efficient way to sort it.

################################### ~ Instructions ~ ###################################
# For the following code to work use the following instructions:
#   1) You will be asked to enter the number of student in your classroom
#   2) You will then be required to enter each of the students names followed 
#      by their behaviour Score out of 10. ( Eg: John5 )  :Name = John, Score = 5
#   3) If you have entered a wrong value, Enter: "  x  ", to end the list.
#      Unfortunately your are going to have to start again with the names and the scores

studentCount = int(input("Enter the amount of students in your class:"))

namesList = []

for i in range (studentCount):
    names = input("Enter the name of your Student followed by their score:")
    names = names.upper()
    namesList.append(names)
    
    if names == 'X':
        print("It appears that you hve made a mistake!\n You are going to have to start over.")
        break
    else:
        print("List Provided:",namesList)
        

slist = sorted(namesList, key=lambda x:x[-1], reverse=True)
print("List Sorted",slist)

CodePudding user response:

I'm not sure if your question has any bearing on the problem you're trying to solve -- but to pair the first and last element, second and second last, etc, you can slice the list in two and zip the first half with the reversed second half:

>>> slist = list(range(10))
>>> slist
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(zip(slist[:len(slist)//2], reversed(slist[len(slist)//2:])))
[(0, 9), (1, 8), (2, 7), (3, 6), (4, 5)]

CodePudding user response:

Alternatively, you can try to use the little trick of index - i and ~i to get the desired pairs: (and it can save some computations...)

Explanations: each index i - if we negate it, it becomes the backwards index.

for i in range(6):
    print(i, ~i)

    
0 -1
1 -2
2 -3
3 -4
4 -5
5 -6

pairs = []

for i in range(len(L)):
    pairs.append((L[i], L[~i]))

L = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# running Output:
print(pairs)

[(0, 9), (1, 8), (2, 7), (3, 6), (4, 5), (5, 4), (6, 3), (7, 2), (8, 1), (9, 0)]

Ex2.

L = [1, 2, 3, 4, 5, 6, 7]
 
# running it with get pairs:
[(1, 7), (2, 6), (3, 5), (4, 4), (5, 3), (6, 2), (7, 1)]

  • Related