[英]How can you iterate through a tuple (str), then return a dictionary containing the keys (from the tuple) and the index of the keys as the values?
[英]How do you turn a tuple with three elements into a dictionary containing a key and two values?
我有一個看起來像這樣的元組:
List=[
('actinium-225', '10', '314'),
('actinium-226', '1.2238', '110'),
('americium-240', '2.117', '395'),
('berkelium-245', '4.94', '182'),
]
無論如何,這個列表還在繼續,所以我一直在尋找如何解壓這些以創建一個字典,以便我可以計算這些元素的放射性衰變率,因為第一個值是元素,第二個是半衰期,第三個是剩余的庫存量(克)。
我需要這樣的東西
Dict={
1: ('actinium 225', 10, 314),
2: ('actinium-226', 1.2238, 110),
3: ('americium-240', 2.117, 395),
4: ('berkelium-245', 4.94, 182),
}
如何將包含三個元素的元組轉換為包含一個鍵和兩個值的字典?
您的問題標題與您預期的 output 不匹配,因此我將僅使用 go 與預期的 output 而不是問題標題。
您可以使用map
並使用字典理解進行enumerate
:
{idx: tuple([item[0]] + list(map(float, item[1:]))) for idx, item in enumerate(List, 1)}
OUTPUT :
{1: ('actinium-225', 10.0, 314.0),
2: ('actinium-226', 1.2238, 110.0),
3: ('americium-240', 2.117, 395.0),
4: ('berkelium-245', 4.94, 182.0)}
如果不需要類型轉換,您可以執行dict(enumerate(List,1))
dic = {}
for index, ele in enumerate(List):
key = index+1
val_2 = float(ele[1])
val_3 = int(ele[2])
dic.update({key: (ele[0], val_2, val_3)})
print(dic)
{1: ('actinium-225', 10.0, 314), 2: ('actinium-226', 1.2238, 110), 3: ('americium-240', 2.117, 395), 4: ('berkelium-245', 4.94, 182)}
您的問題的答案是微不足道的,您可以使用諸如理解、生成的表達式、map / 過濾器等工具隨心所欲地轉換您的可迭代對象,無論您喜歡什么。
這是一種代碼高爾夫:
Dict = {i: (el, float(hl), int(st)) for i, (el, hl, st) in enumerate(List, 1)}
然而,
老實說,我不明白這一點。 如果你認為你需要一個字典,它的鍵只是有序的int
數字,你不需要dict
,你需要一個list
!
而且您已經將它們放在list
。 您可以通過索引檢索值,如List[2]
,非常類似於(甚至更好)從dict
檢索它們,如Dict[2]
。
你可以遍歷元組並創建一個字典,像這樣
elements = [('actinium-225', '10', '314'), ('actinium-226', '1.2238', '110'), ('americium-240', '2.117', '395'), ('berkelium-245', '4.94', '182')]
elemDict = {}
for ind, tup in enumerate(elements):
elemDict[ind+1] = tup
具有enumerate
和data destruction
的簡單for-loop
:
l = [
('actinium-225', '10', '314'),
('actinium-226', '1.2238', '110'),
('americium-240', '2.117', '395'),
('berkelium-245', '4.94', '182'),
]
d = {}
for i, (a, b, c) in enumerate(l, 1):
d[i] = (a, float(b), int(c))
print(d)
'''
{1: ('actinium-225', 10.0, 314),
2: ('actinium-226', 1.2238, 110),
3: ('americium-240', 2.117, 395),
4: ('berkelium-245', 4.94, 182)}
'''
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.