我有一個list
其中包含sorted tuples
based
在2nd element
元組。提供排名數字包含python排序元組列表
樣品名單如下:
[ ('not', 48),
('this', 47),
('which', 45),
('by', 45),
('as', 44),
('are', 42),
('will', 41),
('i', 40),
('but', 38),
('all', 38),
('with', 34) ]
我需要提供rank_number到每個元組如下:
[ ('not', 48, 1),
('this', 47, 2),
('which', 45, 3),
('by', 45, 3),
('as', 44, 5),
('are', 42, 6),
('will', 41, 7),
('i', 40, 8),
('but', 38, 9),
('all', 38, 9),
('with', 34, 11) ]
我試着寫for循環和第二個元素對方,但並不在比較在第二元素相同的情況下獲得適當的排名。
,我試過的代碼如下:
sorted_rank_words = []
rank_number = 1
list1 = sorted_words
count1 = 0
count2 = 0
for x in sorted_words:
r1 = list1.index(x)
list1.pop(r1)
for y in list1:
if x[1] > y[1]:
count1 = count1 + 1
elif x[1] == y[1]:
count2 = count2 + 1
if count1 > 0:
sorted_rank_words.append(x+(rank_number,))
rank_number = rank_number + 1
elif count2 > 0:
sorted_rank_words.append(x+(rank_number,))
rank_number = rank_number + count2
count1 = 0
count2 = 0
向我們展示您編寫的代碼! – Elmex80s
@ Elmex80s更新了帖子。請檢查。 –