[英]how do i remove the Nth element from my list until there's only one element remains and print that remaining element in python
[英]How do I remove the element with fewest sets in a list and only keep the one with the most?
我有一個列表,其中每個元素都包含未知數量的集合。 (列表中的集合因用戶在程序中所做的選擇而異。)現在我想刪除所有集合最少的元素,只保留一個或包含最多集合的元素。
我的列表可能如下所示:
[{'Chocolate'}, {'Chocolate'}, {'JellyBean', 'Chips'}]
在這種情況下,我只想保留最后一個元素,因為它包含兩個集合,其余的只有一個集合。 但有時有幾個元素的集合數最多,然后我想保留它們。
我試圖做類似的事情:
if min(len(list)) != max(len(list)):
list.remove(min(len(list)))
但是 Python 只是說“'int' 對象不可迭代” ,我可以理解為什么但不知道如何思考。
如果有人幫助我將非常感謝!
您需要迭代列表一次以確定最大值,然后再次查找要保留的元素。 將會有更好的解決方案來以最有效的方式完成它,但會更難理解。
example_list = [('Chocolate'), ('Chocolate'), ('JellyBean', 'Chips')]
max_length = 0
for item in example_list:
if len(item) > max_length:
max_length = len(item)
new_list = []
for item in example_list:
if len(item) == max_length:
new_list.append(item)
您可能可以刪除,但通常 Python 會因為更改您正在積極迭代的內容而生氣。
為什么不創建一個新列表,其中包含最大數量的元素。 試試下面:
list_of_sets= [{'Chocolate'}, {'Chocolate', 'Candy'}, {'JellyBean', 'Chips'}]
max_len=max(len(s) for s in list_of_sets)
final_list = [s for s in list_of_sets if len(s)==max_len]
final_list
結果:
[{'Candy', 'Chocolate'}, {'Chips', 'JellyBean'}]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.