我正在嘗試將串列中的第一個和最后一個值、第二個和倒數第二個數字等配對。我可以手動完成:
list = [ slist[0], slist[-1] ]
list1 = [ slist[1], slist[-2] ]
但對我來說,這里的問題是我正在輸入學生人數,我不知道串列包含多少值,我試圖找到一種有效的方法來對其進行排序。
################################### ~ 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)
uj5u.com熱心網友回復:
我不確定您的問題是否與您要解決的問題有任何關系——但是要將第一個和最后一個元素、第二個和倒數第二個等配對,您可以將串列分成兩部分和zip前半部分reversed下半場:
>>> 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)]
uj5u.com熱心網友回復:
或者,您可以嘗試使用 index - i和~i的小技巧來獲得所需的對:(它可以節省一些計算......)
說明:每個索引 i - 如果我們否定它,它就會成為向后索引。
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)]
例 2。
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)]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/530677.html
標籤:Python列表排序
上一篇:隨機耗盡元素串列而不先隨機排序
