請幫我從串列 VideoList 中減去現有的字串,這樣我們就有區別了,應該格式化成一個新的串列
Database = ["vill du ha","garry", "yao"] #this is the list of the local data we have
VideoList = ["garry", "vill du ha", "yao", "potato"] #this list has the same data as Database or more
#My code:
if len(VideoList) == len(Database):
print("No new videos")
else:
new_List = #i don't know what to do here but i want the list VideoLise to subtract the existing string in Data base and return what's left from VideoList as a List so the output should be NewList = ["potato"]
uj5u.com熱心網友回復:
您可以將兩個串列轉換為集合并使用集合差異運算子:
diff = set(VideoList) - set(Database)
if diff:
new_list = list(diff)
print(new_list)
else:
print("No new videos")
輸出:
['potato']
uj5u.com熱心網友回復:
您可以檢查 VideoList 的元素是否存在于資料庫中
Database = ["vill du ha","garry", "yao"]
VideoList = ["garry", "vill du ha", "yao", "potato"]
if len(VideoList) == len(Database):
print("No new videos")
else:
new_list=[]
for element in VideoList:
if not element in Database:
new_list.append(element)
uj5u.com熱心網友回復:
而不是else你可以這樣做: elif len(VideoList) > len(Database): print(f"you have {len(VideoList) - len(Database)} new videos")
uj5u.com熱心網友回復:
這是使用集合運算子“差異”的一個很好的例子。將您的串列轉換為集合,獲取差異,然后將結果轉換回串列:
>>> Database = ["vill du ha","garry", "yao"]
>>> VideoList = ["garry", "vill du ha", "yao", "potato"]
>>> new_list = list(set(VideoList).difference(set(Database)))
>>> new_list
['potato']
uj5u.com熱心網友回復:
檢查資料庫中是否存在,如果不存在,則附加到臨時串列 temp
def differ(VideoList, Database):
temp = []
for video in VideoList:
if video not in Database:
temp.append(video)
return temp
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/388319.html
