[英]New list of not repeated elements
我想創建一個以 lsit 作為參數的函數,例如:
list = ['a','b','a','d','e','f','a','b','g','b']
並返回特定數量的列表元素(我選擇了數字),這樣沒有數字出現兩次。 例如,如果我選擇 3:
new_list = ['a','b','d']
我嘗試了以下方法:
def func(j, list):
new_list=[]
for i in list:
while(len(new_list)<j):
for k in new_list:
if i != k:
new_list.append(i)
return new_list
但是該函數經歷了無限循環。
嘗試這個。
lst = ['a','b','a','d','e','f','a','b','g','b']
j = 3
def func(j,list_):
new_lst = []
for a in list_:
if a not in new_lst:
new_lst.append(a)
return new_lst[:j]
print(func(j,lst)) # ['a', 'b', 'd']
我不知道為什么有人不發布numpy.unique
解決方案
這是內存有效的方式(我認為😉)。
import numpy as np
lst = ['a','b','a','d','e','f','a','b','g','b']
def func(j,list_):
return np.unique(list_).tolist()[:j]
print(func(3,lst)) # ['a', 'b', 'd']
def func(j, mylist):
# dedup, preserving order (dict is insertion-ordered as a language guarantee as of 3.7):
deduped = list(dict.fromkeys(mylist))
# Slice off all but the part you care about:
return deduped[:j]
如果大輸入的性能是一個問題,那是次優的(即使在j
遠小於輸入的輸入的前j
個索引中找到j
個唯一元素,它也會處理整個輸入),因此可以使用更復雜的解決方案以獲得最大效率。 首先,復制itertools
unique_everseen
配方:
from itertools import filterfalse, islice # At top of file, filterfalse for recipe, islice for your function
def unique_everseen(iterable, key=None):
"List unique elements, preserving order. Remember all elements ever seen."
# unique_everseen('AAAABBBCCDAABBB') --> A B C D
# unique_everseen('ABBCcAD', str.lower) --> A B C D
seen = set()
seen_add = seen.add
if key is None:
for element in filterfalse(seen.__contains__, iterable):
seen_add(element)
yield element
else:
for element in iterable:
k = key(element)
if k not in seen:
seen_add(k)
yield element
現在用islice
包裝它,只提取所需數量的元素,並在擁有它們后立即退出(根本不處理其余的輸入):
def func(j, mylist): # Note: Renamed list argument to mylist to avoid shadowing built-in
return list(islice(unique_everseen(mylist), j))
list
是python中的保留字。
如果元素的順序不是問題,那么
def func(j, user_list):
return list(set(user_list))[:j]
使用“列表”作為變量名是不好的做法
你可以通過在 python 中使用 Counter 庫來解決這個問題
from collections import Counter
a=['a','b','a','d','e','f','a','b','g','b']
b = list(Counter(a))
print(b[:3])
所以你的功能將是這樣的
def unique_slice(list_in, elements):
new_list = list(Counter(list_in))
print("New list: {}".format(new_list))
if int(elements) <= len(new_list):
return new_list[:elements]
return new_list
希望它能解決你的問題
正如其他人所說,您不應該使用 Shadow 內置名稱“列表”。 因為這可能會導致很多問題。 這是一個簡單的問題,您應該添加到新列表並檢查元素是否已添加。
python 中的 [:] 運算符可讓您沿索引分隔列表。
>>>l = [1, 2, 3, 4]
>>>l[:1]
[1]
>>>l[1:]
[2, 3, 4]
lst = ['a', 'b', 'a', 'd', 'e', 'f', 'a', 'b', 'g', 'b']
def func(number, _list):
out = []
for a in _list:
if a not in out:
out.append(a)
return out[:number]
print(func(4, lst)) # ['a', 'b', 'd', 'e']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.