我需要一個函式的幫助,該函式輸出一個字典,其中包含 R1 和 R2 之間的組合,它的輸出代表 R2 ? R1
到目前為止,我有
def composition(R1,R2):
d = {i:R2[R1[i]] for i in R1}
print(d)
此功能有效輸入
R1 = {1:'a',2:'b',3:'c'}
R2 = {'a':'A','b':'B','c':'C'}
output: {1: 'A', 2: 'B', 3: 'C'}
我需要作業的是
R1 = {1 : [2, 3], 2 : [3], 3 : [4], 4 : [1, 3]}
R2 = {1 : [3], 2 : [1, 4], 3 : [2], 4 : [1, 2]}
output should be: R2 ? R1 = {1 : [1, 2, 4], 2 : [2], 3 : [1, 2], 4 : [2, 3]}
我得到的是不可散列的型別串列
任何幫助都會很棒,謝謝。
uj5u.com熱心網友回復:
由于 R1 和 R2 的值都是串列,因此您需要嵌套推導來獲取每個鍵的扁平結果中的所有映射元素:
R1 = {1 : [2, 3], 2 : [3], 3 : [4], 4 : [1, 3]}
R2 = {1 : [3], 2 : [1, 4], 3 : [2], 4 : [1, 2]}
output = {k1:[n2 for n1 in v1 for n2 in R2[n1]] for k1,v1 in R1.items()}
print(output)
{1: [1, 4, 2], 2: [2], 3: [1, 2], 4: [3, 2]}
uj5u.com熱心網友回復:
單獨使用串列理解在 Python 中撰寫有點令人費解(也許通過使用functools.reduce折疊子串列可以提高可讀性),但它應該是這樣的:
def composition(R1, R2):
d = {
i: [
val
for sublist in [R2[j] for j in R1[i]]
for val in sublist
]
for i in R1
}
print(d)
uj5u.com熱心網友回復:
這是適用于兩種情況的通用解決方案。
總之,檢查該值是否為非字串可迭代并組合所有元素,否則僅組合該值。
from collections.abc import Iterable
from itertools import chain
def composition(R1, R2):
return {k1: list(chain(*[R2[e] for e in v1]))
if isinstance(v1, Iterable)
and not isinstance(v1, str)
else v1
for k1,v1 in R1.items()}
示例 1:
>>> R1 = {1:'a',2:'b',3:'c'}
>>> R2 = {'a':'A','b':'B','c':'C'}
>>> composition(R1, R2)
{1: 'a', 2: 'b', 3: 'c'}
示例 2:
>>> R1 = {1 : [2, 3], 2 : [3], 3 : [4], 4 : [1, 3]}
>>> R2 = {1 : [3], 2 : [1, 4], 3 : [2], 4 : [1, 2]}
>>> composition(R1, R2)
{1: [1, 4, 2], 2: [2], 3: [1, 2], 4: [3, 2]}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/311461.html
