import random
from itertools import repeat
races_per_season = {
'2015' : "19",
'2016' : "21",
'20116' : "21",
'2017' : "20",
'2018' : "21",
'2019' : "21",
'2020' : "17",
'2021' : "16"
}
tmp_list = list(repeat(random.sample(range(80),10), 156))
total_races = 0
for k,v in races_per_season.items():
while total_races < int(v):
tmp_list[total_races].insert(1, k)
total_races = 1
break # inserting breaks here and below, somewhat works, but only gives me the first year throughout the list
break
for x in tmp_list:
print(x)
我正在嘗試使用 dict 值遍歷串列串列并將鍵插入到索引 1 處的串列中。但是,無論我如何嘗試,它似乎都在迭代并將所有鍵插入串列然后移到串列中下一個...
這是我看到的結果......但是通過添加上面的中斷,這將在 156 個串列的整個串列中繼續......并且在串列 19 中不會改變
[[29, '2015', 56, 39, 31, 25, 37, 5, 16, 8, 73],
[29, '2015', 56, 39, 31, 25, 37, 5, 16, 8, 73],
[29, '2015', 56, 39, 31, 25, 37, 5, 16, 8, 73],
[29, '2015', 56, 39, 31, 25, 37, 5, 16, 8, 73]]
但我想要的結果如下。
[[29, '2015', 56, 39, 31, 25, 37, 5, 16, 8, 73],
[29, '2015', 56, 39, 31, 25, 37, 5, 16, 8, 73],
[29, '2015', 56, 39, 31, 25, 37, 5, 16, 8, 73],
[29, '2015', 56, 39, 31, 25, 37, 5, 16, 8, 73],
[29, '2015', 56, 39, 31, 25, 37, 5, 16, 8, 73],
[29, '2015', 56, 39, 31, 25, 37, 5, 16, 8, 73]...
并繼續 '2015' 19 次,然后將 '2016' 插入以下 21 等中。 . dict 中的所有值總和為 len(tmp_list) 156 的值
任何幫助將不勝感激。謝謝
uj5u.com熱心網友回復:
檢查這個
import random
from itertools import repeat
races_per_season = {
'2015' : "19",
'2016' : "21",
'20116' : "21",
'2017' : "20",
'2018' : "21",
'2019' : "21",
'2020' : "17",
'2021' : "16"
}
# this line to create 156 lists that are not sharing the same reference
tmp_list = [list(arr) for arr in repeat(random.sample(range(80),10), 156)]
i = 0
for k,v in races_per_season.items():
total_races = 0
while total_races < int(v):
tmp_list[i].insert(0, k)
tmp_list[i].insert(0, int(v))
total_races = 1
i =1
for x in tmp_list:
print(x)
uj5u.com熱心網友回復:
您可以先創建一個單獨的年份串列,然后將年份添加到每個串列中
years = [k for k, v in races_per_season.items() for i in range(int(v))]
res = [[years[idx]] lst for idx, lst in enumerate(tmp_list)]
print(res)
uj5u.com熱心網友回復:
你可以試試這個,至少似乎對我有用。
import random
from itertools import repeat
races_per_season = {
'2015' : "19",
'2016' : "21",
'20116' : "21",
'2017' : "20",
'2018' : "21",
'2019' : "21",
'2020' : "17",
'2021' : "16"
}
tmp_list = list(repeat(random.sample(range(80), 10), 156))
seasons = [season for season, races in races_per_season.items()
for i in range(int(races))]
tmp_list = [[L[0], seasons[i], *L[1:]] for i, L in enumerate(tmp_list)]
for x in tmp_list:
print(x)
結果:
[44, '2015', 18, 33, 30, 54, 22, 53, 19, 4, 68]
...repeated 18 times
[44, '2016', 18, 33, 30, 54, 22, 53, 19, 4, 68]
...repeated 20 times
...
解釋
在上述方法的第一部分中,我們使用兩個list理解來構建years變數。第一個理解迭代字典中的鍵值對,第二個理解迭代0...n-1每個鍵的值中的所有數字- 例如,我們有鍵 '2015' n=19。
解釋使用的以下語法:
[L[0], seasons[i], *L[1:]]
這基本上說:
- 創建一個包含第一個元素的新串列
L,它是其中的子串列tmp_list - 添加我們正在迭代的季節作為第二個元素
- 該
[1:]說,讓我在子串列中的所有元素,除了第一個元素。星號*運算子再次解包該結果,因此例如我們不會在每個串列中得到一個串列。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/330660.html
上一篇:如何區分Javascript中的串列和物件?[復制]
下一篇:如何從串列或系列創建可變深度字典
