![](/img/trans.png)
[英]How to use letters based on pseudo-random numbers to encode a given string, using lists, string methods, dictionaries?
[英]Print variables in order based on pseudo-random numbers
我正在創建一個任務,其中一個人根據他們的准確性獲得分數。 然后他們會看到一個屏幕,顯示他們在其他玩家中的表現位置(其他玩家的分數是隨機生成的數字。)
我需要為假玩家生成隨機分數,然后以某種方式根據他們的位置按降序對分數進行排序。 顯示的唯一真實分數將是 [sub_score]。
以下是我到目前為止所擁有的。 我不確定如何根據它們的值對這些變量進行排序,然后打印 [firstplace]、[secondplace]、[thirdplace] 等的變量。此外,這需要發生 4 次,每次都有不同的分數為假玩家生成,並且他們的位置在任務中波動。 這些隨機生成的數字應介於 70-90 之間,因為這些分數反映了准確性。
import random
'jsw_score' = random.randint(70,90)
'jbp_score' = random.randint(70,90)
'bsp_score' = random.randint(70,90)
'mjk_score' = random.randint(70,90)
'phs_score' = random.randint(70,90)
'msw_score' = random.randint(70,90)
'tdl_score' = random.randint(70,90)
'aik_score' = random.randint(70,90)
'wjc_score' = random.randint(70,90)
'sub_score' = accuracy
謝謝!
有幾件事:1)不確定您使用sub_score
做什么。 2)您需要更好的數據結構以避免重復代碼。 我在下面使用了字典。
import random
dd = {}
for i in [
'jsw_score',
'jbp_score',
'bsp_score',
'mjk_score',
'phs_score',
'msw_score',
'tdl_score',
'aik_score',
'wjc_score']:
dd[i] = random.randint(70,90)
# sort by score
for item in sorted(dd.items(), key=lambda x: x[1], reverse=True):
print item
示例輸出:
('aik_score', 90)
('tdl_score', 89)
('jsw_score', 88)
('wjc_score', 87)
('msw_score', 84)
('jbp_score', 82)
('bsp_score', 81)
('mjk_score', 79)
('phs_score', 73)
按照您的方式創建單個變量將使這項任務變得非常困難。 它也很難擴展。 想想如果你有一百或一千分會發生什么!
相反,請仔細考慮您的要求並選擇能夠滿足您所有要求的適當數據結構。 許多結構甚至可以自動排序。
假設您有一組鍵:jsw_score、jbp_score 等,它首先適合使用字典結構。 您可以像這樣靜態構建字典:
scores = {'jsw_score':random.randint(70,90),
'jbp_score':random.randint(70,90),
...}
或者,如果您有字典無法滿足的其他要求,那么您可以在文檔中閱讀此頁面並選擇適當的數據結構。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.