[英]Get Unique Value from List of Objects in Python
我正在嘗試通過 For 循環獲取 python 腳本中的對象列表,如下所示:
for org in Details:
file.write("Organization Name : %s \n" % (org.orgName))
file.write("Name : %s \n" % (org.repoName))
file.write(" URL : %s \n" % (org.repoURL))
output 出來就像:
Organization Name : A
Name : B
URL : C
Organization Name : A
Name : B
Organization Name : D
Name : E
URL : F
Organization Name : D
Name : E
URL : F
Organization Name : D
Name : E
URL : F
如何確保只打印唯一值? 我期待的 output:
Organization Name : A
Name : B
URL : C
Organization Name : D
Name : E
URL : F
不要立即寫入文件。 在循環中,將詳細信息存儲在數據結構中,一組 toples (orgname,name,url) 或者如果您的一個詳細信息是唯一的,請使用字典並使用例如組織名稱作為鍵和 tople(name,url)作為價值。
dictionnary = dict()
for org in Details:
dictionnary[org.orgName] = [org.repoName,org.repoURL]
for key in dict.Keys():
file.write("Organization Name : %s \n" % (key))
file.write("Name : %s \n" % (dictionnary[key][0]))
file.write(" URL : %s \n" % (dictionnary[key][1]))
然后 go 通過字典的所有元素並像您一樣寫入文件中。
我不確定第二個解決方案是否會起作用,具體取決於詳細信息中的內容。 除了在 for 循環之前,你的代碼中什么都不改變,寫
Details=set(Details)
for org in Details:
file.write("Organization Name : %s \n" % (org.orgName))
file.write("Name : %s \n" % (org.repoName))
file.write(" URL : %s \n" % (org.repoURL))
提醒:集合是沒有重復的未排序值的列表
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.