[英]Searching for Equivalence Among Elements of a List
我有以下代碼
Trans_Func = [['s1', '@', 's2'], ['s1', '@', 's4'], ['s2', '0', 's2'], ['s2', '1', 's3'], ['s3', '0', 's3'], ['s3', '1', 's3'], ['s3', '2', 's3'], ['s4', '1', 's4'], ['s4', '2', 's4'], ['s4', '2', 's5']]
new_rules = []
for i, j in Trans_Func:
if i[0] == j[0] and i[1] == j[1]:
#operation to append the new rule
print(new_rules)
我正在嘗試創建一個包含 Trans_Func 元素的新列表,僅當第一個字符串相等時,第二個字符串相等,但第三個字符串不同。 我對 new_rules 的預期 output 是:
new_rules = [['s1', '@', 's1, s4'], ['s4', '2', 's4, s5']]
我只是不知道如何遍歷 Trans_Func 以嘗試同時檢查多個元素。
給你 go
for i in range(len(Trans_Func)):
IF i<len(Trans_Func)-1:
if Trans_Func[i][1]==Trans_Func[i+1][1] and Trans_Func[i][2]==Trans_Func[i+1][2]:
#operation to append the new rule
您可以使用字典將匹配對作為鍵來管理,並將列表中的第三個字符串作為值累積。 然后遍歷字典以隔離具有多個關聯的第三個字符串的對:
d = dict()
for s1,s2,s3 in Trans_Func: d.setdefault((s1,s2),[]).append(s3)
new_rules = [ [s1,s2,", ".join(ss)] for (s1,s2),ss in d.items() if len(ss)>1 ]
print(new_rules)
[['s1', '@', 's2, s4'], ['s4', '2', 's4, s5']]
給你的變量一個合適的名字(小寫且有意義),比如trans_list
(例如)。
使用有效的生成器表達式和zip
function:
trans_list = [['s1', '@', 's2'], ['s1', '@', 's4'], ['s2', '0', 's2'], ['s2', '1', 's3'], ['s3', '0', 's3'],
['s3', '1', 's3'], ['s3', '2', 's3'], ['s4', '1', 's4'], ['s4', '2', 's4'], ['s4', '2', 's5']]
new_rules = list([lst_1[0], lst_1[1], lst_1[2] + ', ' + lst_2[2]]
for lst_1, lst_2 in zip(trans_list[:-1], trans_list[1:])
if lst_1[:2] == lst_2[:2] and lst_1[2] != lst_2[2])
print(new_rules)
output:
[['s1', '@', 's2, s4'], ['s4', '2', 's4, s5']]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.